import React, { useState, useRef, useCallback, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { Settings, FileText, LogOut, X } from 'lucide-react'
import PrizeDisplay from '../components/PrizeDisplay'
import ResultDisplay from '../components/ResultDisplay'
import ScreenKeyboard from '../components/ScreenKeyboard'
import LotteryAnimation from '../components/LotteryAnimation'
import ErrorBoundary from '../components/ErrorBoundary'
import { useAppStore } from '../store'
import { useToastContext } from '../contexts/ToastContext'
import LotteryService from '../services/lotteryService'
import EventService, { EVENT_TYPES } from '../services/eventService'

const Lottery: React.FC = () => {
  const navigate = useNavigate()
  const { logout, prizes, drawResult, isDrawing, resetDraw, startDraw, currentStudentId, setStudentId } = useAppStore()
  const { showWarning } = useToastContext()
  const [showCountdown, setShowCountdown] = useState(false)
  const [showAnimation, setShowAnimation] = useState(false)
  const [errorMessage, setErrorMessage] = useState('')
  const [showPasswordModal, setShowPasswordModal] = useState(false)
  const [password, setPassword] = useState('')
  const [passwordError, setPasswordError] = useState('')
  
  // 验证抽奖次数并开始倒计时
  const handleDrawStart = async () => {
    const lotteryService = LotteryService.getInstance()
    const validation = await lotteryService.canStudentDraw(currentStudentId)
    
    console.log('=== 抽奖验证调试 ===')
    console.log('当前学号:', currentStudentId)
    console.log('验证结果:', validation)
    console.log('是否可以抽奖:', validation.canDraw)
    console.log('提示消息:', validation.message)
    
    if (!validation.canDraw) {
      // 显示气泡提示
      console.log('显示Toast提示:', validation.message)
      // 根据不同的错误类型使用不同的标题
      const title = validation.message.includes('格式不正确') ? '学号格式错误' : 
                   validation.message.includes('抽奖上限') ? '抽奖次数限制' : 
                   validation.message.includes('系统配置') ? '系统错误' : '抽奖验证'
      showWarning(title, validation.message, 5000)
      return false
    }
    
    console.log('🎲 验证通过，准备开始抽奖，学号:', currentStudentId)
    console.log('🎯 抽奖前奖品状态:', prizes.map(p => ({ name: p.name, remaining: p.remainingQuantity })))
    
    setErrorMessage('')
    // 不在这里设置showAnimation，应该在倒计时完成后设置
    return true
  }
  
  // 防止重复调用的引用
  const isStartingDrawRef = useRef(false)
  const isCountdownCompleteRef = useRef(false)
  
  // 倒计时完成处理
  const handleCountdownComplete = useCallback(async () => {
    console.log('⏰ ===== 倒计时完成处理开始 =====');
    console.log('⏰ 当前时间戳:', Date.now());
    console.log('⏰ 当前状态 - isDrawing:', isDrawing);
    console.log('⏰ 当前学号:', currentStudentId);
    console.log('⏰ 当前drawResult:', drawResult);
    console.log('⏰ startDraw函数类型:', typeof startDraw);
    
    // 防止重复调用倒计时完成处理
    if (isCountdownCompleteRef.current) {
      console.log('⏰ 倒计时完成处理正在进行中，跳过重复调用');
      return;
    }
    
    isCountdownCompleteRef.current = true;
    
    console.log('⏰ 倒计时完成，开始执行抽奖逻辑');
    
    if (!currentStudentId) {
      console.error('⏰ 学号为空，无法进行抽奖');
      isCountdownCompleteRef.current = false;
      return;
    }

    // 防止重复调用
    if (isDrawing) {
      console.log('⏰ 抽奖正在进行中，跳过重复调用');
      isCountdownCompleteRef.current = false;
      return;
    }

    console.log('⏰ 准备调用startDraw，参数检查:');
    console.log('⏰ - 学号:', currentStudentId);
    console.log('⏰ - 学号类型:', typeof currentStudentId);
    console.log('⏰ - 学号长度:', currentStudentId.length);

    try {
      console.log('⏰ 开始调用startDraw函数...');
      const result = await startDraw(currentStudentId);
      console.log('⏰ startDraw调用完成，返回结果:', result);
      console.log('⏰ 结果类型:', typeof result);
      console.log('⏰ 结果详情:', JSON.stringify(result, null, 2));
      console.log('⏰ 抽奖完成后的状态 - isDrawing:', isDrawing, 'drawResult:', drawResult);
    } catch (error) {
      console.error('⏰ 抽奖过程中发生错误:', error);
      console.error('⏰ 错误堆栈:', error.stack);
    } finally {
      // 重置防重复调用标志
      isCountdownCompleteRef.current = false;
    }
    
    console.log('⏰ ===== 倒计时完成处理结束 =====');
  }, [currentStudentId, startDraw, isDrawing, drawResult]) // 修复：移除showCountdown依赖，避免重复触发
  
  // 处理学号输入变化
  const handleStudentIdChange = (studentId: string) => {
    console.log('学号输入变化:', studentId)
    // 学号变化时的处理逻辑，如果需要的话
  }
  
  // 处理倒计时开始
  const handleCountdownStart = async () => {
    console.log('🎯 倒计时开始')
    console.log('当前状态 - showCountdown:', showCountdown, 'isDrawing:', isDrawing)
    
    try {
      const canStart = await handleDrawStart()
      console.log('🎯 handleDrawStart返回结果:', canStart)
      
      if (canStart) {
        console.log('✅ 验证通过，只设置showAnimation为true，不设置showCountdown')
        // 修复：只设置showAnimation，不设置showCountdown，避免重复倒计时
        setShowAnimation(true)  // 显示抽奖动画，动画内部会处理倒计时
        console.log('✅ 状态更新后 - showAnimation: true')
        return true
      } else {
        console.log('❌ 验证失败，无法开始倒计时')
        return false
      }
    } catch (error) {
      console.error('❌ handleCountdownStart出错:', error)
      return false
    }
  }
  
  // 处理清空结果
  const handleClearResult = () => {
    console.log('清空抽奖结果')
    resetDraw()
  }
  
  // 处理密码提交
  const handlePasswordSubmit = async () => {
    console.log('验证后台管理密码:', password);
    try {
      const lotteryService = LotteryService.getInstance();
      const isValid = await lotteryService.validateAdminPassword(password);
      
      if (isValid) {
        setShowPasswordModal(false)
        setPassword('')
        setPasswordError('')
        navigate('/admin')
      } else {
        setPasswordError('后台管理密码错误，请重试！')
        setPassword('')
      }
    } catch (error) {
      setPasswordError('验证失败，请重试！')
      setPassword('')
    }
  }

  // 合并抽奖结果监听和事件订阅，减少useEffect数量
  React.useEffect(() => {
    // 监听抽奖结果变化，向测试页面发送结果
    if (drawResult) {
      try {
        window.parent.postMessage({
          type: 'LOTTERY_RESULT',
          result: drawResult
        }, '*');
      } catch (error) {
        // 静默处理错误
      }
    }

    // 设置事件监听
    const eventService = EventService.getInstance();
    
    // 监听奖品数据更新
    const unsubscribePrizes = eventService.subscribe(EVENT_TYPES.PRIZES_UPDATED, () => {
      // 奖品数据通过store自动更新，无需手动处理
    });

    // 监听抽奖记录更新
    const unsubscribeRecords = eventService.subscribe(EVENT_TYPES.RECORDS_UPDATED, () => {
      // 记录更新可能影响用户抽奖次数限制，但这里主要用于日志记录
    });

    return () => {
      unsubscribePrizes();
      unsubscribeRecords();
    };
  }, [drawResult]);

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-900 to-gray-800 relative">
      {/* 顶部导航栏 */}
      <div className="absolute top-4 right-4 flex gap-2 z-10">

        <button
          onClick={() => setShowPasswordModal(true)}
          className="flex items-center gap-2 px-4 py-2 bg-gray-700 text-gray-200 rounded-lg shadow-md hover:shadow-lg hover:bg-gray-600 transition-all duration-200"
        >
          <Settings size={18} />
          后台管理
        </button>
        <button
          onClick={() => navigate('/records')}
          className="flex items-center gap-2 px-4 py-2 bg-gray-700 text-gray-200 rounded-lg shadow-md hover:shadow-lg hover:bg-gray-600 transition-all duration-200"
        >
          <FileText size={18} />
          记录查询
        </button>
        <button
          onClick={() => {
            logout()
            navigate('/login')
          }}
          className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg shadow-md hover:shadow-lg hover:bg-red-700 transition-all duration-200"
        >
          <LogOut size={18} />
          退出登录
        </button>
      </div>

      {/* 主要内容区域 */}
      <div className="flex h-screen">
        {/* 左侧区域 - 奖项展示 */}
        <div className="w-[22.22%] p-4">
          <PrizeDisplay prizes={prizes || []} />
        </div>
        
        {/* 中间结果展示 - 增大到45% */}
        <div className="w-[45%] h-full p-4">
          <ErrorBoundary>
            <ResultDisplay 
              drawResult={drawResult} 
              onRestart={resetDraw}
              isDrawing={isDrawing}
              showCountdown={showCountdown}
              onCountdownComplete={handleCountdownComplete}
            />
          </ErrorBoundary>
        </div>
        
        {/* 右侧抽奖区域 - 缩小到32.78% */}
        <div className="w-[32.78%] h-full p-4">
          <div className="bg-gray-800/50 backdrop-blur-md rounded-2xl p-8 h-full flex flex-col border border-gray-700/50">
            <div className="flex-1 flex flex-col justify-center items-center">
              <ScreenKeyboard 
                onStudentIdChange={handleStudentIdChange}
                onDrawStart={handleDrawStart}
                onCountdownStart={handleCountdownStart}
                onClearResult={handleClearResult}
              />
              
              {/* 错误提示 */}
              {errorMessage && (
                <div className="mt-4 p-4 bg-red-500/20 border border-red-500/30 rounded-lg">
                  <p className="text-red-300 text-center font-medium">{errorMessage}</p>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
      
      {/* 抽奖动画浮窗 */}
      <LotteryAnimation 
        isVisible={showAnimation}
        onComplete={() => {
          console.log('🎲 LotteryAnimation onComplete 被调用，隐藏动画框');
          setShowAnimation(false);
          
          // 抽奖完成后，触发奖项数据更新
          console.log('🎲 抽奖完成，触发奖项数据更新');
          const eventService = EventService.getInstance();
          eventService.emit(EVENT_TYPES.PRIZES_UPDATED, {
            updatedPrizes: null, // 触发重新加载
            timestamp: Date.now()
          });
        }}
        onCountdownComplete={handleCountdownComplete}
        result={drawResult}
      />
      
      {/* 密码输入弹窗 */}
      {showPasswordModal && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50">
          <div className="bg-gray-800 rounded-2xl p-6 w-96 border border-gray-700 shadow-2xl">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-xl font-semibold text-white">后台管理验证</h3>
              <button
                onClick={() => {
                  setShowPasswordModal(false)
                  setPassword('')
                  setPasswordError('')
                }}
                className="text-gray-400 hover:text-white transition-colors"
              >
                <X size={20} />
              </button>
            </div>
            
            <div className="mb-4">
              <label className="block text-gray-300 text-sm font-medium mb-2">
                请输入后台管理密码：
              </label>
              <input
                type="password"
                value={password}
                onChange={(e) => {
                  setPassword(e.target.value)
                  setPasswordError('')
                }}
                onKeyPress={(e) => {
                  if (e.key === 'Enter') {
                    handlePasswordSubmit()
                  }
                }}
                className="w-full px-4 py-2 bg-gray-700 border border-gray-600 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                placeholder="输入密码"
                autoFocus
              />
              {passwordError && (
                <p className="text-red-400 text-sm mt-2">{passwordError}</p>
              )}
            </div>
            
            <div className="flex gap-3">
              <button
                onClick={() => {
                  setShowPasswordModal(false)
                  setPassword('')
                  setPasswordError('')
                }}
                className="flex-1 px-4 py-2 bg-gray-600 text-gray-200 rounded-lg hover:bg-gray-500 transition-colors"
              >
                取消
              </button>
              <button
                onClick={handlePasswordSubmit}
                className="flex-1 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
              >确认</button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default Lottery