import React, { useState, useEffect, useRef, useCallback } from 'react';
import { X } from 'lucide-react';
import { DrawResult, useAppStore } from '../store';
import ConfettiEffect from './ConfettiEffect';

interface LotteryAnimationProps {
  isVisible: boolean;
  onComplete: () => void;
  onCountdownComplete?: () => void;
  result?: DrawResult;
}

const LotteryAnimation: React.FC<LotteryAnimationProps> = ({
  isVisible,
  onComplete,
  onCountdownComplete,
  result
}) => {
  const [animationPhase, setAnimationPhase] = useState<'countdown' | 'loading' | 'result' | 'hidden'>('hidden');
  const [showConfetti, setShowConfetti] = useState(false);
  const [forceRender, setForceRender] = useState(0);
  const [countdownNumber, setCountdownNumber] = useState(3);
  const [scrollingIndex, setScrollingIndex] = useState(0);
  const [isCountdownRunning, setIsCountdownRunning] = useState(false); // 添加倒计时执行标志
  
  // 调试日志：状态变化追踪
  useEffect(() => {
    console.log('🎲📊 状态更新 - animationPhase:', animationPhase, 'countdownNumber:', countdownNumber, 'isVisible:', isVisible);
  }, [animationPhase, countdownNumber, isVisible]);
  
  const scrollTimerRef = useRef<NodeJS.Timeout | null>(null);
  const onCountdownCompleteRef = useRef(onCountdownComplete);
  const onCompleteRef = useRef(onComplete);
  const animationPhaseRef = useRef(animationPhase);
  const resultRef = useRef(result);
  
  // 从store获取奖项数据
  const { prizes } = useAppStore();
  
  // 倒数数字列表
  const countdownNumbers = [3, 2, 1];
  
  // 更新ref引用
  useEffect(() => {
    onCountdownCompleteRef.current = onCountdownComplete;
    onCompleteRef.current = onComplete;
    animationPhaseRef.current = animationPhase;
    resultRef.current = result;
  });

  // 清理定时器函数
  const clearTimer = useCallback(() => {
    if (scrollTimerRef.current) {
      clearTimeout(scrollTimerRef.current);
      scrollTimerRef.current = null;
    }
  }, []);

  // 开始倒计时效果 - 使用更稳定的实现
  const startCountdownEffect = useCallback(() => {
    // 防止重复执行倒计时
    if (isCountdownRunning) {
      console.log('🎲⚠️ 倒计时正在执行中，跳过重复调用');
      return;
    }
    
    console.log('🎲🎲🎲 ===== 开始倒计时流程 =====');
    console.log('🎲 启动倒计时效果');
    setIsCountdownRunning(true); // 设置执行标志
    setAnimationPhase('countdown');
    setCountdownNumber(3);
    console.log('🚀 开始倒计时动画，初始数字: 3');
    window.postMessage({ type: 'COUNTDOWN_START', number: 3 }, '*');
    
    // 清理之前的定时器
    console.log('🎲 清理之前的定时器');
    clearTimer();
    
    // 使用简单的定时器序列，避免递归和闭包问题
    console.log('🎲🎯 显示数字 3');
    
    // 1秒后显示2
    scrollTimerRef.current = setTimeout(() => {
      console.log('🎲🎯 显示数字 2');
      setCountdownNumber(2);
      console.log('🔢 倒计时: 2');
      window.postMessage({ type: 'COUNTDOWN_NUMBER', number: 2 }, '*');
      
      // 再1秒后显示1
      scrollTimerRef.current = setTimeout(() => {
        console.log('🎲🎯 显示数字 1');
        setCountdownNumber(1);
        console.log('🔢 倒计时: 1');
        window.postMessage({ type: 'COUNTDOWN_NUMBER', number: 1 }, '*');
        
        // 再1秒后触发抽奖
        scrollTimerRef.current = setTimeout(() => {
          console.log('🎲🚀 倒计时完成，触发抽奖回调');
          
          // 倒计时完成，切换到loading状态
          console.log('🎯 倒计时321完成！切换到loading状态');
          setAnimationPhase('loading');
          setCountdownNumber(null);
          setIsCountdownRunning(false); // 重置执行标志
          
          // 触发倒计时完成回调
          if (onCountdownCompleteRef.current) {
            console.log('🎯 触发倒计时完成回调');
            onCountdownCompleteRef.current();
          }
          
          console.log('🎲🎲🎲 ===== 倒计时流程完成 =====');
          
          // 5秒后如果还没有结果，则隐藏动画框
           setTimeout(() => {
             // 使用ref获取最新状态，检查当前状态，如果还在loading且没有结果，则隐藏
             console.log('🎲🔍 检查当前状态 - phase:', animationPhaseRef.current, 'hasResult:', !!resultRef.current);
             if (animationPhaseRef.current === 'loading' && !resultRef.current) {
               console.log('🚫 超时隐藏动画框 - 倒计时完成后无结果');
               window.postMessage({ type: 'ANIMATION_HIDDEN', reason: 'timeout' }, '*');
               setAnimationPhase('hidden');
               if (onCompleteRef.current) {
                 onCompleteRef.current();
               }
             } else {
               console.log('🎲✅ 状态已变化或已有结果，无需隐藏');
             }
           }, 5000); // 5秒后检查
        }, 1000);
      }, 1000);
    }, 1000);
  }, [clearTimer, isCountdownRunning]); // 添加isCountdownRunning依赖


  // 重置动画状态
  const resetAnimation = useCallback(() => {
    console.log('🎲 重置动画状态');
    clearTimer(); // 确保清理定时器
    setAnimationPhase('hidden');
    setShowConfetti(false);
    setCountdownNumber(3);
    setScrollingIndex(0);
    setIsCountdownRunning(false); // 重置执行标志
    setForceRender(prev => prev + 1);
  }, [clearTimer]);



  // 主要状态管理useEffect - 只监听isVisible的变化
  useEffect(() => {
    console.log('🎲🔄 LotteryAnimation状态变化:', { isVisible, result: !!result, animationPhase });
    
    if (isVisible) {
      // 只有在隐藏状态时才启动倒计时，避免重复触发
      if (animationPhase === 'hidden') {
        console.log('🎲🚀 准备启动倒计时');
        startCountdownEffect();
      }
    } else if (!isVisible && animationPhase !== 'hidden') {
      console.log('🎲🔒 隐藏动画，重置状态');
      resetAnimation();
    }
  }, [isVisible]); // 修复：只监听isVisible，不监听animationPhase，避免重复触发

  // 组件卸载时清理定时器
  useEffect(() => {
    return () => {
      clearTimer();
    };
  }, [clearTimer]);

  // 监听结果变化 - 当有结果时切换到结果显示阶段
  useEffect(() => {
    if (result && (animationPhase === 'loading' || animationPhase === 'countdown')) {
      // 如果正在倒数，让倒数完成后再显示结果
      if (animationPhase === 'countdown') {
        return;
      }
      
      console.log('🎲📋 收到抽奖结果，切换到结果显示阶段:', result);
      // 直接显示结果
      setAnimationPhase('result');
      
      // 只有1等奖才显示撒花效果
      const shouldShowConfetti = result.success && result.prize && result.prize.level === 1;
      setShowConfetti(shouldShowConfetti);
      
      // 3秒后隐藏撒花效果
      if (shouldShowConfetti) {
        const confettiTimer = setTimeout(() => {
          setShowConfetti(false);
        }, 3000);
        
        return () => clearTimeout(confettiTimer);
      }
    }
    
    // 添加超时机制：如果在loading状态超过10秒没有结果，自动隐藏
    if (animationPhase === 'loading' && !result) {
      console.log('🎲⏰ 设置loading状态超时检查');
      const timeoutTimer = setTimeout(() => {
        console.log('🎲⏰ Loading状态超时，自动隐藏动画框');
        setAnimationPhase('hidden');
        if (onCompleteRef.current) {
          onCompleteRef.current();
        }
      }, 10000); // 10秒超时
      
      return () => clearTimeout(timeoutTimer);
    }
  }, [result, animationPhase]);

  const handleClose = useCallback(() => {
    clearTimer();
    setAnimationPhase('hidden');
    setShowConfetti(false);
    setCountdownNumber(3);
    setScrollingIndex(0);
    setIsCountdownRunning(false); // 重置执行标志
    setForceRender(prev => prev + 1);
    if (onCompleteRef.current) {
      onCompleteRef.current();
    }
  }, [clearTimer]);

  if (!isVisible && animationPhase === 'hidden') {
    console.log('🚫 LotteryAnimation组件已隐藏 - 倒计时修复成功！');
    return null;
  }

  // 渲染不同阶段的内容
  const renderContent = () => {
    switch (animationPhase) {
      case 'countdown':
        return (
          <div className="text-center">
            <div className="mb-8">
              <div className="text-4xl text-white mb-6 font-bold">抽奖即将开始</div>
              <div className="bg-gradient-to-r from-red-500 to-pink-500 rounded-full w-40 h-40 mx-auto flex items-center justify-center shadow-2xl">
                <div className="text-8xl font-bold text-white animate-bounce" key={`countdown-${countdownNumber}`}>
                  {countdownNumber}
                </div>
              </div>
              <div className="text-lg text-gray-300 mt-6">
                请准备好，抽奖马上开始...
              </div>
            </div>
          </div>
        );
      
      case 'loading':
        return (
          <div className="text-center">
            <div className="animate-spin rounded-full h-24 w-24 border-b-4 border-yellow-400 mx-auto mb-6"></div>
            <div className="text-3xl text-white mb-4 font-bold">
              正在抽奖中...
            </div>
            <div className="text-lg text-gray-300">
              请稍候，系统正在为您抽取奖品
            </div>
          </div>
        );
      
      case 'result':
        if (!result) {
          return (
            <div className="text-center">
              <div className="text-3xl text-white mb-6 font-bold">
                抽奖完成，但未获取到结果
              </div>
              <button 
                onClick={onComplete}
                className="px-8 py-3 bg-blue-500 text-white text-xl rounded-lg hover:bg-blue-600 font-bold"
              >
                确定
              </button>
            </div>
          );
        }
        
        return (
          <div className="text-center">
            {result.success && result.prize ? (
              <>
                <div className="text-8xl font-bold text-yellow-400 mb-6 animate-bounce">🎉 恭喜中奖！🎉</div>
                <div className="text-6xl text-white mb-4 font-bold">
                  您获得了：{result.prize.name}
                </div>
                <div className="text-4xl text-gray-300 mb-6">
                  {result.message}
                </div>
              </>
            ) : (
              <>
                <div className="text-4xl font-bold text-gray-400 mb-6">很遗憾，未中奖</div>
                <div className="text-2xl text-gray-300 mb-6">
                  {result.message || '感谢您的参与，下次再来！'}
                </div>
              </>
            )}
            
            <button 
              onClick={onComplete}
              className="px-8 py-3 bg-blue-500 text-white text-xl rounded-lg hover:bg-blue-600 transition-colors font-bold"
            >确定</button>
          </div>
        );
      
      default:
        return null;
    }
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-80 flex items-center justify-center z-50">
      <div className="w-4/5 h-1/2 flex items-center justify-center p-8">
        {renderContent()}
      </div>

      
      {/* 撒花特效 */}
      <ConfettiEffect 
        isActive={showConfetti} 
        duration={4000}
      />
    </div>
  );
};

export default LotteryAnimation;