import React, { useEffect, useState, useRef, useCallback } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { Trophy, Gift, Award, Star, Clock, User } from 'lucide-react'
import { Prize } from '../store'
import { useAppStore } from '../store'
import ApiService from '../services/apiService'
import EventService, { EVENT_TYPES } from '../services/eventService'

interface PrizeDisplayProps {
  prizes: Prize[]
}

// 中奖记录接口
interface DrawRecord {
  id: string
  student_id: string
  prize_id: string
  prize_name: string
  draw_time: string
}

const PrizeDisplay: React.FC<PrizeDisplayProps> = ({ prizes: propsPrizes }) => {
  const { loadPrizes, prizes: storePrizes } = useAppStore();
  const [drawRecords, setDrawRecords] = useState<DrawRecord[]>([]);
  const [isLoadingRecords, setIsLoadingRecords] = useState(false);
  const [isAutoRefreshing, setIsAutoRefreshing] = useState(true);
  const [lastRefreshTime, setLastRefreshTime] = useState<Date | null>(null);
  const [refreshError, setRefreshError] = useState<string | null>(null);
  const [retryCount, setRetryCount] = useState(0);
  const [isPageVisible, setIsPageVisible] = useState(true);
  const [refreshInterval, setRefreshInterval] = useState(5000); // 动态刷新间隔
  const refreshIntervalRef = useRef<NodeJS.Timeout | null>(null);
  const retryTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const isComponentMountedRef = useRef(true);
  const lastRequestTimeRef = useRef<number>(0);
  const debounceTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  
  // 使用store中的prizes数据，如果没有则使用props传入的数据
  const prizes = storePrizes && storePrizes.length > 0 ? storePrizes : propsPrizes;
  
  // 调试日志已移除以优化控制台输出
  
  // 检测网络连接状态
  const checkNetworkStatus = useCallback(() => {
    return navigator.onLine;
  }, []);

  // 获取错误类型和用户友好的错误消息
  const getErrorInfo = useCallback((error: any) => {
    if (!checkNetworkStatus()) {
      return {
        type: 'network',
        message: '网络连接已断开，请检查网络设置',
        canRetry: true
      };
    }
    
    if (error instanceof TypeError && error.message.includes('fetch')) {
      return {
        type: 'connection',
        message: '无法连接到服务器，请稍后重试',
        canRetry: true
      };
    }
    
    if (error instanceof Error) {
      if (error.message.includes('404')) {
        return {
          type: 'not_found',
          message: 'API接口不存在，请联系管理员',
          canRetry: false
        };
      }
      
      if (error.message.includes('500')) {
        return {
          type: 'server_error',
          message: '服务器内部错误，请稍后重试',
          canRetry: true
        };
      }
      
      if (error.message.includes('timeout')) {
        return {
          type: 'timeout',
          message: '请求超时，请检查网络连接',
          canRetry: true
        };
      }
    }
    
    return {
      type: 'unknown',
      message: error instanceof Error ? error.message : '未知错误',
      canRetry: true
    };
  }, [checkNetworkStatus]);

  // 加载中奖记录（带错误处理和重试机制）
  const loadDrawRecords = useCallback(async (isBackground = false) => {
    if (!isComponentMountedRef.current) return;
    
    try {
      if (!isBackground) {
        setIsLoadingRecords(true);
      }
      setRefreshError(null);
      setRetryCount(0); // 重置重试计数
      
      const apiService = ApiService.getInstance();
      const records = await apiService.getAllRecords();
      
      if (isComponentMountedRef.current) {
        setDrawRecords(records || []);
        setLastRefreshTime(new Date());
        console.log('✅ 中奖记录加载成功，共', records?.length || 0, '条记录');
      }
    } catch (error) {
      console.error('❌ 中奖记录加载失败:', error);
      if (isComponentMountedRef.current) {
        const errorInfo = getErrorInfo(error);
        setRefreshError(errorInfo.message);
        
        // 增加重试计数
        setRetryCount(prev => prev + 1);
        
        // 只有在可以重试且是后台刷新且重试次数不超过3次时才进行自动重试
        if (errorInfo.canRetry && isBackground && isAutoRefreshing && retryCount < 3) {
          const retryDelay = Math.min(3000 * Math.pow(2, retryCount), 30000); // 指数退避，最大30秒
          console.log(`🔄 将在 ${retryDelay/1000} 秒后重试加载中奖记录 (第${retryCount + 1}次重试)`);
          retryTimeoutRef.current = setTimeout(() => {
            loadDrawRecords(true);
          }, retryDelay);
        }
      }
    } finally {
      if (isComponentMountedRef.current && !isBackground) {
        setIsLoadingRecords(false);
      }
    }
  }, [isAutoRefreshing, getErrorInfo, retryCount]);

  // 防抖加载函数
  const debouncedLoadRecords = useCallback((isBackground = false) => {
    const now = Date.now();
    const timeSinceLastRequest = now - lastRequestTimeRef.current;
    
    // 清除之前的防抖定时器
    if (debounceTimeoutRef.current) {
      clearTimeout(debounceTimeoutRef.current);
      debounceTimeoutRef.current = null;
    }
    
    // 防止过于频繁的请求（最小间隔2秒）
    if (timeSinceLastRequest < 2000) {
      debounceTimeoutRef.current = setTimeout(() => {
        if (isComponentMountedRef.current) {
          lastRequestTimeRef.current = Date.now();
          loadDrawRecords(isBackground);
        }
      }, 2000 - timeSinceLastRequest);
      return;
    }
    
    lastRequestTimeRef.current = now;
    loadDrawRecords(isBackground);
  }, [loadDrawRecords]);

  // 动态调整刷新间隔
  const adjustRefreshInterval = useCallback(() => {
    if (!isPageVisible) {
      // 页面不可见时，降低刷新频率到30秒
      setRefreshInterval(30000);
    } else if (refreshError) {
      // 有错误时，增加刷新间隔到10秒
      setRefreshInterval(10000);
    } else {
      // 正常情况下5秒刷新
      setRefreshInterval(5000);
    }
  }, [isPageVisible, refreshError]);

  // 启动自动刷新定时器
  const startAutoRefresh = useCallback(() => {
    if (refreshIntervalRef.current) {
      clearInterval(refreshIntervalRef.current);
    }
    
    if (isAutoRefreshing && isPageVisible) {
      refreshIntervalRef.current = setInterval(() => {
        debouncedLoadRecords(true); // 后台刷新
      }, refreshInterval);
      // 自动刷新已启动
    }
  }, [isAutoRefreshing, isPageVisible, refreshInterval, debouncedLoadRecords]);

  // 停止自动刷新
  const stopAutoRefresh = useCallback(() => {
    if (refreshIntervalRef.current) {
      clearInterval(refreshIntervalRef.current);
      refreshIntervalRef.current = null;
      // 自动刷新已停止
    }
    if (retryTimeoutRef.current) {
      clearTimeout(retryTimeoutRef.current);
      retryTimeoutRef.current = null;
    }
    if (debounceTimeoutRef.current) {
      clearTimeout(debounceTimeoutRef.current);
      debounceTimeoutRef.current = null;
    }
  }, []);

  // 页面可见性监听
  useEffect(() => {
    const handleVisibilityChange = () => {
      const isVisible = !document.hidden;
      const wasVisible = isPageVisible;
      setIsPageVisible(isVisible);
      
      if (isVisible && !wasVisible) {
        // 只有从不可见变为可见时才刷新数据，避免重复请求
        console.log('📱 页面变为可见，刷新数据');
        // 延迟一下再刷新，避免与其他请求冲突
        setTimeout(() => {
          if (isComponentMountedRef.current) {
            debouncedLoadRecords(true);
          }
        }, 500);
      } else if (!isVisible) {
        console.log('📱 页面变为不可见');
      }
    };
    
    document.addEventListener('visibilitychange', handleVisibilityChange);
    
    return () => {
      document.removeEventListener('visibilitychange', handleVisibilityChange);
    };
  }, [debouncedLoadRecords, isPageVisible]);

  // 动态调整刷新间隔
  useEffect(() => {
    adjustRefreshInterval();
  }, [adjustRefreshInterval]);

  // 合并初始化和自动刷新逻辑，减少useEffect数量
  useEffect(() => {
    const initializeData = async () => {
      try {
        console.log('🎯 PrizeDisplay: 开始加载奖项数据');
        await loadPrizes();
        console.log('✅ PrizeDisplay: 奖项数据加载成功');
      } catch (error) {
        console.error('❌ PrizeDisplay: 奖项数据加载失败:', error);
        const errorInfo = getErrorInfo(error);
        setRefreshError(errorInfo.message);
      }
      
      // 延迟加载中奖记录，避免并发请求
      setTimeout(() => {
        if (isComponentMountedRef.current) {
          loadDrawRecords();
        }
      }, 100);
      
      // 延迟启动自动刷新
      setTimeout(() => {
        if (isComponentMountedRef.current && refreshInterval > 0) {
          startAutoRefresh();
        }
      }, 1000);
    };
    
    initializeData();
    
    // 组件卸载时清理
    return () => {
      isComponentMountedRef.current = false;
      stopAutoRefresh();
    };
  }, []);

  // 监听刷新间隔变化，单独处理
  useEffect(() => {
    if (refreshInterval > 0 && !isAutoRefreshing && isComponentMountedRef.current) {
      startAutoRefresh();
    }
  }, [refreshInterval, startAutoRefresh, isAutoRefreshing]);

  // WebSocket监听中奖记录更新
  useEffect(() => {
    const eventService = EventService.getInstance();
    
    // 监听新增中奖记录
    const handleNewRecord = (event: CustomEvent) => {
      const { record } = event.detail;
      if (record && isComponentMountedRef.current) {
        setDrawRecords(prev => [record, ...prev]);
        setLastRefreshTime(new Date());
        setRefreshError(null);
        // 收到新中奖记录
      }
    };
    
    // 监听中奖记录更新
    const handleRecordsUpdated = (event: CustomEvent) => {
      const records = event.detail;
      if (Array.isArray(records) && isComponentMountedRef.current) {
        setDrawRecords(records);
        setLastRefreshTime(new Date());
        setRefreshError(null);
        // 中奖记录已更新
      }
    };
    
    // 监听数据清空
    const handleDataClear = () => {
      if (isComponentMountedRef.current) {
        setDrawRecords([]);
        setLastRefreshTime(new Date());
        setRefreshError(null);
        // 中奖记录已清空
      }
    };
    
    // 监听奖项更新事件
    const handlePrizesUpdated = (event: CustomEvent) => {
      console.log('PrizeDisplay: 收到奖项更新事件', event.detail);
      if (isComponentMountedRef.current) {
        // 重新加载奖项数据
        loadPrizes().catch(error => {
          console.error('PrizeDisplay: 奖项更新后重新加载失败:', error);
        });
      }
    };
    
    eventService.subscribe('new_record', handleNewRecord);
    eventService.subscribe('records_updated', handleRecordsUpdated);
    eventService.subscribe('data_cleared', handleDataClear);
    eventService.subscribe('system_reset', handleDataClear);
    eventService.subscribe('force_reset', handleDataClear);
    eventService.subscribe('prizes_updated', handlePrizesUpdated);
    
    return () => {
      eventService.unsubscribe('new_record', handleNewRecord);
      eventService.unsubscribe('records_updated', handleRecordsUpdated);
      eventService.unsubscribe('data_cleared', handleDataClear);
      eventService.unsubscribe('system_reset', handleDataClear);
      eventService.unsubscribe('force_reset', handleDataClear);
      eventService.unsubscribe('prizes_updated', handlePrizesUpdated);
    };
  }, []);
  
  // 过滤活跃奖项
  const activePrizes = prizes.filter(prize => prize.is_active);

  // 获取奖项图标
  const getPrizeIcon = (level: number) => {
    switch (level) {
      case 1:
        return <Trophy className="w-8 h-8" />
      case 2:
        return <Award className="w-8 h-8" />
      case 3:
        return <Star className="w-8 h-8" />
      default:
        return <Gift className="w-8 h-8" />
    }
  }
  
  // 获取奖项等级文字
  const getLevelText = (level: number) => {
    const levelMap: { [key: number]: string } = {
      1: '特等奖',
      2: '一等奖',
      3: '二等奖',
      4: '三等奖',
      5: '参与奖'
    }
    return levelMap[level] || `${level}等奖`
  }
  
  // 计算剩余比例
  const getRemainingRatio = (prize: Prize) => {
    return prize.totalQuantity > 0 ? (prize.remainingQuantity / prize.totalQuantity) * 100 : 0
  }
  
  // 获取状态颜色
  const getStatusColor = (ratio: number) => {
    if (ratio > 50) return 'text-green-400'
    if (ratio > 20) return 'text-yellow-400'
    if (ratio > 0) return 'text-orange-400'
    return 'text-red-400'
  }
  
  // 根据奖项等级获取字体大小
  const getFontSizeClass = (prizeName: string) => {
    if (prizeName.includes('一等奖') || prizeName.includes('特等奖')) {
      return 'text-lg' // 一等奖最大
    } else if (prizeName.includes('二等奖')) {
      return 'text-base' // 二等奖次之
    } else if (prizeName.includes('三等奖')) {
      return 'text-sm' // 三等奖再次
    } else if (prizeName.includes('参与') || prizeName.includes('重在参与')) {
      return 'text-xs' // 重在参与最小
    }
    return 'text-sm' // 默认大小
  }
  
  // 格式化学号显示（每4位一个空格）
  const formatStudentId = (studentId: string) => {
    return studentId.replace(/(\d{4})(?=\d)/g, '$1 ');
  };
  
  // 格式化时间显示
  const formatTime = (timeString: string) => {
    const date = new Date(timeString);
    return date.toLocaleString('zh-CN', {
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  };
  
  // 判断是否为一等奖
  const isFirstPrize = (prizeName: string) => {
    return prizeName.includes('一等奖') || prizeName.includes('特等奖');
  };
  
  // 如果没有奖项数据，显示加载状态或错误信息
  if (!prizes || prizes.length === 0) {
    console.log('PrizeDisplay 渲染 - 没有奖项数据，显示加载状态');
    return (
      <div className="bg-white/10 backdrop-blur-md rounded-2xl p-4 h-full flex flex-col">
        <h2 className="text-xl font-bold text-white mb-4 text-center">
          奖项设置
        </h2>
        
        <div className="flex-1 flex items-center justify-center">
          <div className="text-center text-white/60">
            {refreshError ? (
              <div className="text-center">
                <div className="w-16 h-16 bg-red-500/20 rounded-full mx-auto mb-4 flex items-center justify-center">
                  <Gift className="w-8 h-8 text-red-400" />
                </div>
                <div className="text-lg mb-2 text-red-300">加载失败</div>
                <div className="text-sm mb-4 text-red-200 max-w-xs mx-auto">
                  {refreshError}
                </div>
                <button 
                  onClick={() => {
                    setRefreshError(null);
                    loadPrizes();
                  }} 
                  className="px-4 py-2 bg-red-500/80 text-white rounded-lg hover:bg-red-500 transition-colors"
                >
                  重试加载
                </button>
              </div>
            ) : (
              <div className="animate-pulse">
                <div className="w-16 h-16 bg-white/20 rounded-full mx-auto mb-4 flex items-center justify-center">
                  <Gift className="w-8 h-8 text-white/40" />
                </div>
                <div className="text-lg mb-2">加载中...</div>
                <button 
                  onClick={() => loadPrizes()} 
                  className="mt-4 px-4 py-2 bg-blue-500/80 text-white rounded-lg hover:bg-blue-500 transition-colors"
                >
                  刷新数据
                </button>
              </div>
            )}
          </div>
        </div>
      </div>
    );
  }
  
  // 如果没有活跃奖项，显示提示信息
  if (activePrizes.length === 0) {
    console.log('PrizeDisplay 渲染 - 没有活跃奖项，显示提示信息');
    return (
      <div className="bg-white/10 backdrop-blur-md rounded-2xl p-4 h-full flex flex-col">
        <h2 className="text-xl font-bold text-white mb-4 text-center">
          奖项设置
        </h2>
        
        <div className="flex-1 flex items-center justify-center">
          <div className="text-center text-white/60">
            <div className="text-lg mb-2">暂无活跃奖项</div>
            <div className="text-sm">所有奖项均已停用</div>
            <button 
              onClick={() => loadPrizes()} 
              className="mt-4 px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
            >
              重新加载
            </button>
          </div>
        </div>
      </div>
    );
  }
  
  return (
    <div className="bg-white/10 backdrop-blur-md rounded-2xl p-4 h-full flex flex-col">
      <h2 className="text-xl font-bold text-white mb-4 text-center">
        奖项设置
      </h2>
      
      <div className="flex-1 space-y-3 overflow-y-auto scrollbar-hide">
        {prizes.filter(prize => prize.is_active).map((prize) => (
          <div
            key={prize.id}
            className="bg-white/5 rounded-xl p-3 border border-white/20"
          >
            <div className="flex items-center justify-between mb-2">
              <h3 className={`${getFontSizeClass(prize.name)} font-semibold text-white truncate`}>
                {prize.name}
              </h3>
              <span className="text-xs text-white/60">
                {(prize.probability * 1000).toFixed(1)}‰
              </span>
            </div>
            
            <div className="flex items-center justify-between text-xs text-white/80 mb-2">
              <span>剩余: {prize.remainingQuantity}</span>
              <span>总数: {prize.totalQuantity}</span>
            </div>
            
            <div className="bg-white/10 rounded-full h-1.5">
              <div
                className="bg-gradient-to-r from-blue-500 to-purple-600 h-1.5 rounded-full transition-all duration-300"
                style={{
                  width: `${(prize.remainingQuantity / prize.totalQuantity) * 100}%`
                }}
              />
            </div>
          </div>
        ))}
      </div>
      
      {/* 中奖记录显示区域 */}
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.6, delay: 0.3 }}
        className="mt-8 flex-1 flex flex-col"
      >
        <div className="bg-white/10 backdrop-blur-sm rounded-2xl p-6 border border-white/20 flex-1 flex flex-col">
          <div className="flex items-center gap-3 mb-4">
            <Trophy className="w-6 h-6 text-yellow-400" />
            <h3 className="text-xl font-bold text-white">中奖记录</h3>
            <div className="flex-1 h-px bg-gradient-to-r from-yellow-400/50 to-transparent"></div>
          </div>
          
          {lastRefreshTime && (
            <div className="mb-3 text-xs text-white/40 text-center">
              最后更新: {lastRefreshTime.toLocaleTimeString()}
            </div>
          )}
          
          {isLoadingRecords ? (
            <div className="flex items-center justify-center py-8">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-yellow-400"></div>
              <span className="ml-3 text-white/70">加载中奖记录...</span>
            </div>
          ) : drawRecords.length === 0 ? (
            <div className="text-center py-8 text-white/50">
              <Award className="w-12 h-12 mx-auto mb-3 opacity-50" />
              <p>暂无中奖记录</p>
            </div>
          ) : (
            <div className={`flex-1 overflow-y-auto overflow-x-hidden space-y-1 scrollbar-thin scrollbar-thumb-white/20 scrollbar-track-transparent transition-opacity duration-500 ${isLoadingRecords ? 'opacity-50' : 'opacity-100'}`}>
              {drawRecords.slice(0, 4).map((record, index) => {
                const isFirst = isFirstPrize(record.prize_name);
                return (
                  <motion.div
                    key={record.id}
                    initial={{ opacity: 0, x: -20 }}
                    animate={{ opacity: 1, x: 0 }}
                    transition={{ duration: 0.5, delay: index * 0.1 }}
                    className={`
                      relative p-2 rounded-lg border transition-all duration-500 hover:shadow-md transform hover:scale-[1.02]
                      ${isFirst 
                        ? 'bg-gradient-to-r from-yellow-500/20 to-orange-500/20 border-yellow-400/50 shadow-lg shadow-yellow-400/20' 
                        : 'bg-white/5 border-white/10 hover:bg-white/10'
                      }
                    `}
                    style={{
                      animationDelay: `${index * 100}ms`,
                      animationFillMode: 'both'
                    }}
                  >
                    {/* 一等奖发光效果 */}
                    {isFirst && (
                      <>
                        <div className="absolute inset-0 rounded-xl bg-gradient-to-r from-yellow-400/10 to-orange-400/10 animate-pulse"></div>
                        <div className="absolute -inset-1 rounded-xl bg-gradient-to-r from-yellow-400/20 to-orange-400/20 blur-sm animate-pulse"></div>
                        <div className="absolute top-2 right-2">
                          <Star className="w-5 h-5 text-yellow-400 animate-pulse" />
                        </div>
                      </>
                    )}
                    
                    <div className="relative z-10 flex flex-wrap items-center gap-2 sm:gap-3">
                      <div className="flex items-center gap-2">
                        <User className="w-4 h-4 text-blue-400" />
                        <span className={`font-mono ${isFirst ? 'text-yellow-100 font-bold' : 'text-white'}`}>
                          {formatStudentId(record.student_id)}
                        </span>
                      </div>
                      
                      <div className="flex items-center gap-2">
                        {isFirst ? (
                          <Trophy className="w-4 h-4 text-yellow-400" />
                        ) : record.prize_name.includes('二等奖') ? (
                          <Award className="w-4 h-4 text-gray-300" />
                        ) : record.prize_name.includes('三等奖') ? (
                          <Gift className="w-4 h-4 text-orange-400" />
                        ) : (
                          <Star className="w-4 h-4 text-blue-400" />
                        )}
                        <span className={`font-semibold ${
                          isFirst 
                            ? 'text-yellow-100 text-lg' 
                            : record.prize_name.includes('二等奖')
                              ? 'text-gray-100'
                              : record.prize_name.includes('三等奖')
                                ? 'text-orange-100'
                                : 'text-blue-100'
                        }`}>
                          {record.prize_name}
                        </span>
                      </div>
                      
                      <div className="flex items-center gap-2 text-sm text-white/70 ml-auto">
                        <Clock className="w-4 h-4" />
                        <span>{formatTime(record.draw_time)}</span>
                      </div>
                    </div>
                    
                    {/* 一等奖额外的装饰效果 */}
                    {isFirst && (
                      <div className="absolute bottom-0 left-0 right-0 h-1 bg-gradient-to-r from-yellow-400 to-orange-400 rounded-b-xl animate-pulse"></div>
                    )}
                  </motion.div>
                );
              })}
            </div>
          )}
        </div>
      </motion.div>
    </div>
  );
};

export default React.memo(PrizeDisplay);