import React, { useState, useEffect } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { Trophy, RefreshCw, Clock, User, Gift, Sparkles } from 'lucide-react'
import { DrawResult } from '../store'
import NetworkStatus from './NetworkStatus'
import ApiService from '../services/apiService'

interface ResultDisplayProps {
  drawResult: DrawResult | null
  onRestart: () => void
  isDrawing: boolean
  showCountdown?: boolean
  onCountdownComplete?: () => void
}

const ResultDisplay: React.FC<ResultDisplayProps> = ({ 
  drawResult, 
  onRestart, 
  isDrawing,
  showCountdown = false,
  onCountdownComplete
}) => {
  // 移除调试日志以优化控制台输出
  
  const [maxDrawTimes, setMaxDrawTimes] = useState<number>(3) // 默认3次
  // 倒计时相关状态已移除，由浮窗LotteryAnimation组件处理
  
  // 获取系统配置中的抽奖次数上限
  useEffect(() => {
    const loadMaxDrawTimes = async () => {
      try {
        const apiService = ApiService.getInstance();
        const config = await apiService.getSystemConfig();
        if (config && config.max_draw_times) {
          setMaxDrawTimes(config.max_draw_times);
        }
      } catch (error) {
        console.error('获取抽奖次数上限失败:', error);
      }
    };
    loadMaxDrawTimes();
  }, []);

  // Props变化监听
  useEffect(() => {
    // 移除调试日志以优化控制台输出
  }, [isDrawing, drawResult])
  const [isCountdownActive, setIsCountdownActive] = useState(false)
  
  // Props变化追踪
  useEffect(() => {
    // 移除调试日志以优化控制台输出
  }, [drawResult, isDrawing, showCountdown]);
  
  // 倒计时逻辑已完全移除，由浮窗LotteryAnimation组件处理
  // 不再在ResultDisplay中显示倒计时，避免与浮窗倒计时重复显示数字3
  
  // 倒计时状态重置逻辑已移除
  // 格式化时间
  const formatTime = (timestamp?: number) => {
    if (!timestamp || typeof timestamp !== 'number') {
      return new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    }
    const date = new Date(timestamp)
    if (isNaN(date.getTime())) {
      return new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    }
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  }
  
  // 格式化学号显示
  const formatStudentId = (studentId?: string) => {
    if (!studentId || typeof studentId !== 'string') return '未知学号'
    if (studentId.length !== 12) return studentId
    return `${studentId.slice(0, 4)}-${studentId.slice(4, 8)}-${studentId.slice(8)}`
  }
  
  return (
    <div className="bg-white/10 backdrop-blur-md rounded-2xl p-4 h-full flex flex-col">
      <div className="mb-4 flex items-center justify-between">
        <h2 className="text-xl font-bold text-white">抽奖结果</h2>
        <NetworkStatus className="bg-black/20 backdrop-blur-sm rounded-lg px-3 py-2" />
      </div>
      
      <div className="flex-1 flex flex-col justify-center">
        <AnimatePresence mode="wait">
          {/* 倒计时状态已移除 - 由浮窗LotteryAnimation组件处理 */}
          {/* 在浮窗倒计时期间，此处不显示任何倒计时内容，避免重复显示 */}
          
          {/* 抽奖中状态 */}
          {isDrawing && !isCountdownActive && (
            <motion.div
              key="drawing"
              initial={{ opacity: 0, scale: 0.9 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.9 }}
              className="text-center space-y-6"
            >
              {/* 旋转圆环 */}
              <div className="relative">
                <motion.div
                  animate={{ rotate: 360 }}
                  transition={{ duration: 2, repeat: Infinity, ease: "linear" }}
                  className="w-20 h-20 border-4 border-blue-500/30 border-t-blue-500 rounded-full mx-auto"
                />
                <div className="absolute inset-0 flex items-center justify-center">
                  <Trophy className="w-8 h-8 text-blue-400" />
                </div>
              </div>
              
              <div>
                <h3 className="text-2xl font-bold text-white mb-2">抽奖进行中</h3>
                <p className="text-white/70">请稍候，正在为您抽取奖品...</p>
              </div>
              
              {/* 动态点 */}
              <div className="flex justify-center space-x-2">
                {Array.from({ length: 3 }).map((_, i) => (
                  <motion.div
                    key={i}
                    className="w-3 h-3 bg-blue-400 rounded-full"
                    animate={{ scale: [1, 1.5, 1], opacity: [0.5, 1, 0.5] }}
                    transition={{
                      duration: 1.5,
                      repeat: Infinity,
                      delay: i * 0.2
                    }}
                  />
                ))}
              </div>
            </motion.div>
          )}
          
          {/* 有结果状态 */}
          {!isDrawing && drawResult && (
            <motion.div
              key="result"
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -20 }}
              className="space-y-6"
            >
              {/* 恭喜标题 */}
              <div className="text-center">
                <motion.div
                  initial={{ scale: 0 }}
                  animate={{ scale: 1 }}
                  transition={{ type: "spring", stiffness: 200, delay: 0.2 }}
                  className="relative inline-block"
                >
                  <div className="text-6xl mb-2">🎉</div>
                  {/* 闪烁效果 */}
                  <motion.div
                    animate={{ scale: [1.5, 2, 1.5], opacity: [0.5, 1, 0.5] }}
                    transition={{ duration: 2, repeat: Infinity }}
                    className="absolute -inset-4 bg-yellow-400/20 rounded-full blur-xl"
                  />
                </motion.div>
                
                <h3 className="text-2xl font-bold text-white mb-1">恭喜中奖！</h3>
                <p className="text-white/70">Congratulations!</p>
              </div>
              
              {/* 奖品信息卡片 */}
              <motion.div
                initial={{ opacity: 0, scale: 0.9 }}
                animate={{ opacity: 1, scale: 1 }}
                transition={{ delay: 0.4 }}
                className="bg-gradient-to-br from-yellow-500/20 to-orange-500/20 rounded-xl p-6 border border-yellow-500/30 relative overflow-hidden"
              >
                {/* 背景装饰 */}
                <div className="absolute top-0 right-0 w-20 h-20 bg-yellow-400/10 rounded-full -translate-y-10 translate-x-10" />
                <div className="absolute bottom-0 left-0 w-16 h-16 bg-orange-400/10 rounded-full translate-y-8 -translate-x-8" />
                
                <div className="relative z-10 text-center space-y-4">
                  {/* 奖品名称 */}
                  <div>
                    <div className="text-3xl font-bold text-yellow-400 mb-1">
                      {drawResult.prize?.name || drawResult.prize?.prize_name || '未知奖品'}
                    </div>
                    <div className="text-white/60 text-sm">获得奖品</div>
                  </div>
                  
                  {/* 分隔线 */}
                  <div className="flex items-center space-x-4">
                    <div className="flex-1 h-px bg-white/20" />
                    <Sparkles className="w-5 h-5 text-yellow-400" />
                    <div className="flex-1 h-px bg-white/20" />
                  </div>
                  
                  {/* 详细信息 */}
                  <div className="space-y-3 text-sm">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center space-x-2 text-white/70">
                        <User className="w-4 h-4" />
                        <span>学号</span>
                      </div>
                      <div className="text-white font-mono">
                        {formatStudentId(drawResult.studentId)}
                      </div>
                    </div>
                    
                    <div className="flex items-center justify-between">
                      <div className="flex items-center space-x-2 text-white/70">
                        <Clock className="w-4 h-4" />
                        <span>时间</span>
                      </div>
                      <div className="text-white text-xs">
                        {formatTime(drawResult.timestamp || Date.now())}
                      </div>
                    </div>
                  </div>
                </div>
              </motion.div>
              
              {/* 重新开始按钮 */}
              <motion.button
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.6 }}
                onClick={onRestart}
                whileHover={{ scale: 1.05 }}
                whileTap={{ scale: 0.95 }}
                className="w-full py-3 bg-gradient-to-r from-blue-500 to-purple-600 hover:from-blue-600 hover:to-purple-700 text-white font-semibold rounded-lg shadow-lg hover:shadow-xl transition-all duration-200 flex items-center justify-center space-x-2"
              >
                <RefreshCw className="w-5 h-5" />
                <span>重新开始</span>
              </motion.button>
            </motion.div>
          )}
          
          {/* 等待状态 */}
          {!isDrawing && !drawResult && (
            <motion.div
              key="waiting"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              className="text-center space-y-6"
            >
              {/* 等待图标 */}
              <div className="relative">
                <div className="w-20 h-20 bg-white/5 rounded-full flex items-center justify-center mx-auto border-2 border-white/10">
                  <Trophy className="w-10 h-10 text-white/30" />
                </div>
                
                {/* 呼吸效果 */}
                <motion.div
                  animate={{ scale: [1, 1.1, 1], opacity: [0.3, 0.6, 0.3] }}
                  transition={{ duration: 3, repeat: Infinity }}
                  className="absolute inset-0 bg-white/5 rounded-full"
                />
              </div>
              
              <div>
                <h3 className="text-xl font-bold text-white/70 mb-2">等待抽奖</h3>
                <p className="text-white/50 text-sm leading-relaxed">
                  请输入12位学号<br />
                  然后点击开始抽奖
                </p>
                <p className="text-white/40 text-xs mt-3">
                  每个学号可以抽奖{maxDrawTimes}次
                </p>
              </div>
              
              {/* 装饰性元素 */}
              <div className="flex justify-center space-x-4">
                {Array.from({ length: 5 }).map((_, i) => (
                  <motion.div
                    key={i}
                    className="w-2 h-2 bg-white/20 rounded-full"
                    animate={{ 
                      scale: [1, 1.5, 1],
                      opacity: [0.3, 0.8, 0.3]
                    }}
                    transition={{
                      duration: 2,
                      repeat: Infinity,
                      delay: i * 0.3
                    }}
                  />
                ))}
              </div>
            </motion.div>
          )}
        </AnimatePresence>
      </div>
      
      {/* 底部提示 */}
      {!isDrawing && !drawResult && (
        <div className="mt-6 pt-4 border-t border-white/10">
          <div className="text-center text-white/40 text-xs space-y-1">
            <p>🎯 输入学号开始抽奖</p>
            <p>🏆 祝您好运连连</p>
          </div>
        </div>
      )}
    </div>
  )
}

export default ResultDisplay