import React, { useState, useCallback, useEffect } from 'react'
import { motion } from 'framer-motion'
import { Play, RotateCcw, Delete, AlertCircle } from 'lucide-react'
import { useAppStore } from '../store'
import LotteryService from '../services/lotteryService'
import type { DrawResult } from '../types'

interface ScreenKeyboardProps {
  onStudentIdChange: (studentId: string) => void
  onDrawStart?: (result: DrawResult) => void
  onCountdownStart?: () => Promise<boolean>
  onClearResult?: () => void
}

const ScreenKeyboard: React.FC<ScreenKeyboardProps> = ({ onStudentIdChange, onDrawStart, onCountdownStart, onClearResult }) => {
  const [studentId, setStudentId] = useState('');
  const [studentDrawCount, setStudentDrawCount] = useState(0);
  const [maxDrawTimes, setMaxDrawTimes] = useState(1);
  const [isCheckingLimit, setIsCheckingLimit] = useState(false);
  const { isDrawing, drawResult, systemConfig } = useAppStore();
  const lotteryService = LotteryService.getInstance();
  
  // 当抽奖结果出现时，清空输入框但不重置抽奖次数状态
  useEffect(() => {
    if (drawResult) {
      setStudentId('');
      onStudentIdChange('');
      // 抽奖完成后重置防抖状态，允许下次抽奖
      setIsDebouncing(false);
      console.log('🎯 抽奖结果出现，重置防抖状态');
      // 不重置抽奖次数状态，让下次输入时重新从API获取最新数据
      // setStudentDrawCount(0); // 移除这行，避免状态不一致
    }
  }, [drawResult, onStudentIdChange]);
  
  // 监听系统配置变化
  useEffect(() => {
    if (systemConfig) {
      setMaxDrawTimes(systemConfig.max_draw_times || 1);
    }
  }, [systemConfig]);
  
  // 监听学号变化，检查抽奖次数
  useEffect(() => {
    const checkStudentDrawCount = async () => {
      if (studentId.length === 12 && /^\d{12}$/.test(studentId)) {
        setIsCheckingLimit(true);
        try {
          // 直接获取学生的实际抽奖次数，而不是依赖canStudentDraw的验证结果
          const apiService = (lotteryService as any).api;
          const student = await apiService.getStudent(studentId);
          const currentDrawCount = student ? student.draw_count : 0;
          setStudentDrawCount(currentDrawCount);
          
          console.log('🔍 检查抽奖次数:', {
            studentId,
            currentDrawCount,
            maxDrawTimes,
            canDraw: currentDrawCount < maxDrawTimes
          });
        } catch (error) {
          console.error('检查抽奖次数失败:', error);
          setStudentDrawCount(0);
        } finally {
          setIsCheckingLimit(false);
        }
      } else {
        // 只有当学号不完整时才重置抽奖次数
        if (studentId.length === 0) {
          setStudentDrawCount(0);
        }
      }
    };
    
    checkStudentDrawCount();
   }, [studentId, maxDrawTimes, lotteryService]);
  
  const handleKeyPress = (key: string) => {
    // 点击数字时清空抽奖结果
    if (onClearResult) {
      onClearResult();
    }
    
    // 如果学号已达到12位，禁用数字键输入
    if (studentId.length >= 12) {
      return;
    }
    
    if (studentId.length < 12) {
      const newStudentId = studentId + key;
      setStudentId(newStudentId);
      onStudentIdChange(newStudentId);
      // 实时更新store中的currentStudentId
      useAppStore.getState().setStudentId(newStudentId);
    }
  };
  
  const handleDelete = () => {
    const newStudentId = studentId.slice(0, -1);
    setStudentId(newStudentId);
    onStudentIdChange(newStudentId);
    // 实时更新store中的currentStudentId
    useAppStore.getState().setStudentId(newStudentId);
  };
  
  const handleClear = () => {
    setStudentId('');
    onStudentIdChange('');
    // 实时更新store中的currentStudentId
    useAppStore.getState().setStudentId('');
  };
  
  // 防抖机制，防止重复点击
  const [isDebouncing, setIsDebouncing] = useState(false);
  
  const handleDraw = useCallback(async () => {
    console.log('🎯 ScreenKeyboard: handleDraw被调用', {
      isDebouncing,
      studentIdLength: studentId.length,
      isDrawing,
      isCheckingLimit,
      studentDrawCount,
      maxDrawTimes,
      onDrawStart: !!onDrawStart,
      onCountdownStart: !!onCountdownStart
    });
    
    // 强化防重复点击检查
    if (isDebouncing || studentId.length !== 12 || isDrawing || isCheckingLimit) {
      console.log('❌ 抽奖条件不满足:', { isDebouncing, studentIdLength: studentId.length, isDrawing, isCheckingLimit });
      return;
    }
    
    // 检查抽奖次数限制
    if (studentDrawCount >= maxDrawTimes) {
      console.log('❌ 已达到抽奖上限:', { studentDrawCount, maxDrawTimes });
      return;
    }
    
    console.log('✅ ScreenKeyboard: 开始抽奖流程', { studentId, studentDrawCount, maxDrawTimes });
    
    // 验证学号格式
    if (!/^\d{12}$/.test(studentId)) {
      console.log('❌ 学号格式不正确');
      return;
    }
    
    try {
      // 立即设置防抖状态，防止重复点击
      console.log('🔒 设置防抖状态');
      setIsDebouncing(true);
      
      // 触发抽奖开始事件
      if (onDrawStart) {
        console.log('📢 触发onDrawStart事件');
        onDrawStart({ 
          success: true,
          message: '',
          student_id: studentId,
          draw_time: new Date().toISOString()
        });
      } else {
        console.log('⚠️ onDrawStart回调不存在');
      }
      
      // 启动倒计时
      if (onCountdownStart) {
        console.log('⏰ 调用onCountdownStart');
        const result = await onCountdownStart();
        console.log('⏰ onCountdownStart返回结果:', result);
        
        // 只有在倒计时成功启动后才重置防抖状态
        if (result) {
          // 延长防抖时间到5秒，确保整个抽奖流程完成
          setTimeout(() => {
            console.log('🔓 重置防抖状态');
            setIsDebouncing(false);
          }, 5000);
        } else {
          // 如果倒计时启动失败，立即重置防抖状态
          console.log('🔓 倒计时启动失败，立即重置防抖状态');
          setIsDebouncing(false);
        }
      } else {
        console.log('⚠️ onCountdownStart回调不存在');
        setIsDebouncing(false);
      }
      
    } catch (error) {
      console.error('❌ ScreenKeyboard: 抽奖启动失败:', error);
      console.error('❌ 错误堆栈:', error.stack);
      setIsDebouncing(false);
      
      // 可以在这里添加用户友好的错误提示
      // 例如通过toast显示错误信息
    }
  }, [studentId, isDrawing, isDebouncing, isCheckingLimit, studentDrawCount, maxDrawTimes, onDrawStart, onCountdownStart]);
  

  const keys = [
    ['1', '2', '3'],
    ['4', '5', '6'],
    ['7', '8', '9'],
    ['clear', '0', 'delete']
  ];

  return (
    <div className="flex flex-col items-center space-y-6">
      {/* 学号显示区域 */}
      <div className="bg-white/10 backdrop-blur-md rounded-2xl p-6 w-full max-w-md">
        <div className="bg-black/20 rounded-xl p-4 mb-4">
          <div className="text-center">
            <div className="text-4xl font-mono text-white mb-2 leading-tight">
              {(() => {
                const paddedId = studentId.padEnd(12, '_');
                const groups = [
                  paddedId.slice(0, 4),
                  paddedId.slice(4, 8),
                  paddedId.slice(8, 12)
                ];
                return groups.map((group, groupIndex) => (
                  <span key={groupIndex} className="inline-block">
                    {group.split('').map((char, charIndex) => (
                      <span key={charIndex} className={char === '_' ? 'text-white/30' : 'text-white'}>
                        {char}
                      </span>
                    ))}
                    {groupIndex < 2 && <span className="text-white/50 mx-1"> </span>}
                  </span>
                ));
              })()}
            </div>
            <div className="text-sm text-white/60">
              {studentId.length}/12
            </div>
          </div>
        </div>
        
        {/* 抽奖次数显示已移除 */}
        
        {/* 抽奖按钮 */}
        <motion.button
          whileHover={{ scale: 1.02 }}
          whileTap={{ scale: 0.98 }}
          onClick={handleDraw}
          disabled={studentId.length !== 12 || isDrawing || isCheckingLimit || studentDrawCount >= maxDrawTimes || isDebouncing}
          className="w-full py-6 bg-gradient-to-r from-green-500 to-blue-600 hover:from-green-600 hover:to-blue-700 disabled:from-gray-500 disabled:to-gray-600 disabled:cursor-not-allowed text-white font-bold text-xl rounded-xl shadow-lg transition-all duration-200 flex items-center justify-center space-x-2"
        >
          <Play className="w-6 h-6" />
          <span>{isDrawing ? '抽奖中...' : 
           isCheckingLimit ? '检查中...' :
           isDebouncing ? '请稍候...' :
           studentDrawCount >= maxDrawTimes ? '已达上限' :
           '开始抽奖'}</span>
        </motion.button>
      </div>
      
      {/* 屏幕键盘 - 140px*140px */}
      <div className="bg-white/10 backdrop-blur-md rounded-2xl p-6">
        <div className="grid grid-cols-3 gap-[10px]" style={{ width: '450px', height: '600px' }}>
          {keys.flat().map((key, index) => {
            let content;
            
            // 检查数字键是否应该被禁用
            const isNumberKeyDisabled = /^[0-9]$/.test(key) && studentId.length >= 12;
            
            const className = `
              rounded-lg font-bold text-sm transition-all duration-200 flex items-center justify-center
              ${isDrawing || isNumberKeyDisabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}
              ${key === 'clear' || key === 'delete' 
                ? 'bg-red-500/20 hover:bg-red-500/30 text-red-300 border border-red-500/30' 
                : isNumberKeyDisabled 
                  ? 'bg-gray-500/20 text-gray-400 border border-gray-500/30'
                  : 'bg-white/10 hover:bg-white/20 text-white border border-white/20'
              }
              ${typeof key === 'number' ? '' : 'text-lg'}
            `;
            
            const numberStyle = /^[0-9]$/.test(key) ? { fontSize: '112px', lineHeight: '140px' } : {};
            
            if (key === 'clear') {
              content = <RotateCcw className="w-8 h-8" />;
            } else if (key === 'delete') {
              content = <Delete className="w-8 h-8" />;
            } else {
              content = key;
            }
            
            return (
              <motion.button
                key={index}
                whileHover={isDrawing || isNumberKeyDisabled ? {} : { scale: 1.05 }}
                whileTap={isDrawing || isNumberKeyDisabled ? {} : { scale: 0.95 }}
                className={className}
                style={{ width: '140px', height: '140px', ...numberStyle }}
                disabled={isDrawing || isNumberKeyDisabled}
                onClick={() => {
                  if (key === 'clear') {
                    handleClear();
                  } else if (key === 'delete') {
                    handleDelete();
                  } else if (!isNumberKeyDisabled) {
                    handleKeyPress(key);
                  }
                }}
              >
                {content}
              </motion.button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

export default React.memo(ScreenKeyboard)