import React, { useEffect, useState } from 'react';
import { motion } from 'framer-motion';
import { Trophy, Award, Star, Gift, RefreshCw, Clock, Sparkles, Wifi, WifiOff } from 'lucide-react';
import { Link } from 'react-router-dom';
import { useAppStore } from '../store';
import { Prize } from '../store';
import EventService, { EVENT_TYPES } from '../services/eventService';
import DatabaseService, { SystemConfig } from '../database/database';
import { websocketService } from '../services/websocketService';
import LoadingSpinner from '../components/LoadingSpinner';
import Empty from '../components/Empty';

interface ProbabilityInfo {
  prize: Prize;
  dynamicProbability: number;
  remainingRatio: number;
  adjustedForDrawLimit: boolean;
}

export default function Home() {
  const { prizes, loadPrizes } = useAppStore();
  const [probabilityData, setProbabilityData] = useState<ProbabilityInfo[]>([]);
  const [lastUpdateTime, setLastUpdateTime] = useState<Date>(new Date());
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [systemConfig, setSystemConfig] = useState<SystemConfig | null>(null);
  const [isWebSocketConnected, setIsWebSocketConnected] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // 计算动态概率 - 结合抽奖次数上限和剩余数量
  const calculateDynamicProbabilities = (prizeList: Prize[]): ProbabilityInfo[] => {
    // 只显示启用且有剩余数量的奖项
    const activePrizes = prizeList.filter(p => p.is_active && p.remainingQuantity > 0);
    
    if (activePrizes.length === 0) {
      return [];
    }

    const maxDrawTimes = systemConfig?.max_draw_times || 1;
    
    // 计算总权重（与抽奖服务的weightedRandomDraw方法一致）
    const totalWeight = activePrizes.reduce((sum, prize) => sum + prize.probability, 0);
    
    return activePrizes.map(prize => {
      // 基础概率计算
      let dynamicProbability = totalWeight > 0 ? (prize.probability / totalWeight) : 0;
      let adjustedForDrawLimit = false;
      
      // 结合抽奖次数上限调整概率
      if (maxDrawTimes > 0) {
        // 计算剩余奖品与最大抽奖次数的比例
        const remainingDrawOpportunities = prize.remainingQuantity;
        const maxPossibleDraws = maxDrawTimes;
        
        // 如果剩余奖品数量远小于可能的抽奖总次数，降低显示概率
        if (remainingDrawOpportunities < maxPossibleDraws * 0.1) {
          dynamicProbability *= (remainingDrawOpportunities / (maxPossibleDraws * 0.1));
          adjustedForDrawLimit = true;
        }
        
        // 如果接近抽奖次数上限，进一步调整概率显示
        if (remainingDrawOpportunities <= maxPossibleDraws * 0.05) {
          dynamicProbability *= 0.5; // 进一步降低显示概率
          adjustedForDrawLimit = true;
        }
      }
      
      const remainingRatio = prize.totalQuantity > 0 ? (prize.remainingQuantity / prize.totalQuantity) * 100 : 0;
      
      return {
        prize,
        dynamicProbability,
        remainingRatio,
        adjustedForDrawLimit
      };
    }).sort((a, b) => a.prize.level - b.prize.level);
  };

  // 获取奖项图标
  const getPrizeIcon = (level: number) => {
    switch (level) {
      case 1:
        return <Trophy className="w-6 h-6" />;
      case 2:
        return <Award className="w-6 h-6" />;
      case 3:
        return <Star className="w-6 h-6" />;
      default:
        return <Gift className="w-6 h-6" />;
    }
  };

  // 获取奖项等级文字
  const getLevelText = (level: number) => {
    const levelMap: { [key: number]: string } = {
      1: '特等奖',
      2: '一等奖',
      3: '二等奖',
      4: '三等奖',
      5: '参与奖'
    };
    return levelMap[level] || `${level}等奖`;
  };

  // 获取概率颜色
  const getProbabilityColor = (probability: number) => {
    if (probability >= 0.3) return 'text-green-400';
    if (probability >= 0.15) return 'text-yellow-400';
    if (probability >= 0.05) return 'text-orange-400';
    return 'text-red-400';
  };

  // 加载系统配置
  const loadSystemConfig = async () => {
    try {
      const db = DatabaseService.getInstance();
      const config = await db.getSystemConfig();
      setSystemConfig(config);
    } catch (error) {
      console.error('加载系统配置失败:', error);
    }
  };

  // 手动刷新概率
  const handleRefresh = async () => {
    setIsRefreshing(true);
    try {
      await loadPrizes();
      await loadSystemConfig();
      setLastUpdateTime(new Date());
      console.log('🔄 手动刷新完成，当前概率数据:', probabilityData);
    } catch (error) {
      console.error('刷新失败:', error);
    } finally {
      setIsRefreshing(false);
    }
  };

  // 调试信息
  useEffect(() => {
    console.log('🏠 首页概率数据更新:', probabilityData);
    console.log('📊 最后更新时间:', lastUpdateTime);
  }, [probabilityData, lastUpdateTime]);

  // 初始化和监听数据变化
  useEffect(() => {
    const initializeData = async () => {
      try {
        setIsLoading(true);
        setError(null);
        await Promise.all([
          loadPrizes(),
          loadSystemConfig()
        ]);
      } catch (err) {
        console.error('初始化数据失败:', err);
        setError('加载数据失败，请刷新页面重试');
      } finally {
        setIsLoading(false);
      }
    };

    initializeData();

    // 监听事件服务的奖品更新事件，实现智能无感刷新
    const eventService = EventService.getInstance();
    const unsubscribeEvent = eventService.subscribe(EVENT_TYPES.PRIZES_UPDATED, () => {
      console.log('WebSocket事件：奖品数据已更新');
      setLastUpdateTime(new Date());
    });

    return () => {
      unsubscribeEvent();
    };
  }, []); // 空依赖数组，避免重复执行

  // 使用useMemo优化概率计算，避免不必要的重新计算
  const memoizedProbabilityData = React.useMemo(() => {
    if (!prizes || prizes.length === 0) return [];
    return calculateDynamicProbabilities(prizes);
  }, [prizes, systemConfig?.max_draw_times]);

  // 只在计算结果真正变化时更新状态
  useEffect(() => {
    const hasChanges = JSON.stringify(memoizedProbabilityData) !== JSON.stringify(probabilityData);
    if (hasChanges) {
      console.log('检测到概率数据变化，更新显示');
      setProbabilityData(memoizedProbabilityData);
      setLastUpdateTime(new Date());
    }
  }, [memoizedProbabilityData, probabilityData]);

  // WebSocket连接状态监控
  useEffect(() => {
    const checkConnection = () => {
      setIsWebSocketConnected(websocketService.isConnected());
    };

    // 初始检查
    checkConnection();

    // 定期检查连接状态
    const interval = setInterval(checkConnection, 5000);

    // 监听WebSocket事件
    const eventService = EventService.getInstance();
    const unsubscribePrizes = eventService.subscribe(EVENT_TYPES.PRIZES_UPDATED, () => {
      setLastUpdateTime(new Date());
      console.log('🔄 WebSocket实时更新: 奖项数据已更新');
    });

    const unsubscribeRecords = eventService.subscribe(EVENT_TYPES.RECORDS_UPDATED, () => {
      setLastUpdateTime(new Date());
      console.log('🔄 WebSocket实时更新: 抽奖记录已更新');
    });

    const unsubscribeSystemConfig = eventService.subscribe(EVENT_TYPES.SYSTEM_CONFIG_UPDATED, () => {
      setLastUpdateTime(new Date());
      console.log('🔄 WebSocket实时更新: 系统配置已更新');
    });

    const unsubscribeDataClear = eventService.subscribe(EVENT_TYPES.DATA_CLEARED, () => {
      setLastUpdateTime(new Date());
      console.log('🔄 WebSocket实时更新: 数据已清空');
    });

    const unsubscribeSystemReset = eventService.subscribe(EVENT_TYPES.SYSTEM_RESET, () => {
      setLastUpdateTime(new Date());
      console.log('🔄 WebSocket实时更新: 系统已重置');
    });

    const unsubscribeForceReset = eventService.subscribe(EVENT_TYPES.FORCE_RESET, () => {
      setLastUpdateTime(new Date());
      console.log('🔄 WebSocket实时更新: 强制重置完成');
    });

    return () => {
      clearInterval(interval);
      unsubscribePrizes();
      unsubscribeRecords();
      unsubscribeSystemConfig();
      unsubscribeDataClear();
      unsubscribeSystemReset();
      unsubscribeForceReset();
    };
  }, []);

  // 加载状态
  if (isLoading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-gray-900 to-gray-800 p-6">
        <div className="max-w-6xl mx-auto">
          <LoadingSpinner size="lg" text="正在加载数据..." fullScreen />
        </div>
      </div>
    );
  }

  // 错误状态
  if (error) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-gray-900 to-gray-800 p-6">
        <div className="max-w-6xl mx-auto">
          <Empty
            title="加载失败"
            description={error}
            action={
              <button
                onClick={() => window.location.reload()}
                className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
              >
                重新加载
              </button>
            }
          />
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-900 to-gray-800 p-6">
      <div className="max-w-6xl mx-auto">
        {/* 标题区域 */}
        <motion.div 
          initial={{ opacity: 0, y: -20 }}
          animate={{ opacity: 1, y: 0 }}
          className="text-center mb-8"
        >
          <h1 className="text-4xl font-bold text-white mb-4">
            抽奖系统 - 实时中奖概率
          </h1>
          <div className="flex items-center justify-center gap-4 text-gray-300 mb-3">
            <div className="flex items-center gap-2">
              {isWebSocketConnected ? (
                <Wifi className="w-4 h-4 text-green-400" />
              ) : (
                <WifiOff className="w-4 h-4 text-red-400" />
              )}
              <span className={isWebSocketConnected ? 'text-green-400' : 'text-red-400'}>
                {isWebSocketConnected ? '实时连接' : '连接断开'}
              </span>
            </div>
            <span>最后更新: {lastUpdateTime.toLocaleTimeString()}</span>
            <button
              onClick={handleRefresh}
              disabled={isRefreshing}
              className="flex items-center gap-2 px-3 py-1 bg-blue-600 hover:bg-blue-700 rounded-lg transition-colors disabled:opacity-50"
            >
              <RefreshCw className={`w-4 h-4 ${isRefreshing ? 'animate-spin' : ''}`} />
              {isRefreshing ? '刷新中...' : '手动刷新'}
            </button>
            <Link
              to="/confetti-demo"
              className="flex items-center gap-2 px-3 py-1 bg-gradient-to-r from-yellow-500 to-orange-500 hover:from-yellow-600 hover:to-orange-600 text-white rounded-lg transition-all duration-300 transform hover:scale-105"
            >
              <Sparkles className="w-4 h-4" />
              撒花演示
            </Link>
          </div>
          {systemConfig && (
            <div className="flex items-center justify-center gap-2 text-yellow-400 text-sm">
              <Clock className="w-4 h-4" />
              <span>每个学号最多可抽奖 {systemConfig.max_draw_times} 次</span>
            </div>
          )}
        </motion.div>

        {/* 概率展示区域 */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {probabilityData.map((item, index) => (
            <motion.div
              key={item.prize.id}
              initial={{ opacity: 0, scale: 0.9 }}
              animate={{ opacity: 1, scale: 1 }}
              transition={{ delay: index * 0.1 }}
              className="bg-white/10 backdrop-blur-md rounded-2xl p-6 border border-white/20 hover:border-white/40 transition-all duration-300"
            >
              {/* 奖项标题 */}
              <div className="flex items-center gap-3 mb-4">
                <div className="text-yellow-400">
                  {getPrizeIcon(item.prize.level)}
                </div>
                <div>
                  <h3 className="text-lg font-semibold text-white">
                    {getLevelText(item.prize.level)}
                  </h3>
                  <p className="text-sm text-gray-300">
                    {item.prize.name}
                  </p>
                </div>
              </div>

              {/* 概率信息 */}
              <div className="space-y-3">
                {/* 动态概率 */}
                <div className="flex justify-between items-center">
                  <span className="text-gray-300">当前中奖概率:</span>
                  <div className="flex items-center gap-2">
                    <span className={`font-bold text-lg ${getProbabilityColor(item.dynamicProbability)}`}>
                      {(item.dynamicProbability * 100).toFixed(2)}%
                    </span>
                    {item.adjustedForDrawLimit && (
                      <span className="text-xs bg-orange-500 text-white px-2 py-1 rounded-full">
                        已调整
                      </span>
                    )}
                  </div>
                </div>

                {/* 原始概率 */}
                <div className="flex justify-between items-center">
                  <span className="text-gray-400 text-sm">配置概率:</span>
                  <span className="text-gray-400 text-sm">
                    {(item.prize.probability * 1000).toFixed(1)}‰
                  </span>
                </div>

                {/* 剩余数量 */}
                <div className="flex justify-between items-center">
                  <span className="text-gray-300">剩余数量:</span>
                  <span className="text-white font-semibold">
                    {item.prize.remainingQuantity} / {item.prize.totalQuantity}
                  </span>
                </div>

                {/* 剩余比例进度条 */}
                <div className="mt-3">
                  <div className="flex justify-between text-xs text-gray-400 mb-1">
                    <span>剩余比例</span>
                    <span>{item.remainingRatio.toFixed(1)}%</span>
                  </div>
                  <div className="bg-gray-700 rounded-full h-2">
                    <div
                      className="bg-gradient-to-r from-blue-500 to-purple-600 h-2 rounded-full transition-all duration-500"
                      style={{ width: `${item.remainingRatio}%` }}
                    />
                  </div>
                </div>
              </div>
            </motion.div>
          ))}
        </div>

        {/* 无奖项提示 */}
        {probabilityData.length === 0 && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            className="py-12"
          >
            <Empty
              title="暂无奖项"
              description="当前没有可抽取的奖项，请联系管理员添加奖项"
              action={
                <button
                  onClick={handleRefresh}
                  disabled={isRefreshing}
                  className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors disabled:opacity-50"
                >
                  <RefreshCw className={`w-4 h-4 ${isRefreshing ? 'animate-spin' : ''}`} />
                  {isRefreshing ? '刷新中...' : '刷新数据'}
                </button>
              }
            />
          </motion.div>
        )}

        {/* 说明文字 */}
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.5 }}
          className="mt-8 text-center text-gray-400 text-sm"
        >
          <p>* 当前中奖概率根据各奖项剩余数量实时计算</p>
          <p>* 系统通过WebSocket实时推送数据更新，无需手动刷新</p>
          <p>* 数据变化时自动更新显示，确保信息准确性</p>
        </motion.div>
      </div>
    </div>
  );
}