import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Plus, Edit, Trash2, Save, X, Settings, LogOut, ChevronDown, ChevronUp, Zap, Database, Wifi, WifiOff, ArrowLeft } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { useAppStore, Prize } from '../store';
import ApiService from '../services/apiService';
import { AuthService } from '../services/authService';
import { PrizeConfig, SystemConfig } from '../database/database';
import { useToast } from '../hooks/useToast';
import websocketService from '../services/websocketService';
import EventService, { EVENT_TYPES } from '../services/eventService';
import LoadingSpinner from '../components/LoadingSpinner';
import Empty from '../components/Empty';

const Admin: React.FC = () => {
  const navigate = useNavigate();
  const { logout, prizes, loadPrizes } = useAppStore();
  const { showSuccess, showError, showWarning } = useToast();
  const [editingPrize, setEditingPrize] = useState<Prize | null>(null);
  const [showAddForm, setShowAddForm] = useState(false);
  const [isWebSocketConnected, setIsWebSocketConnected] = useState(false);
  const [formData, setFormData] = useState({
    prize_name: '',
    prize_level: 1,
    total_quantity: 1,
    probability: 0.1,
    is_active: true
  });
  const [loading, setLoading] = useState(false);
  const [systemConfig, setSystemConfig] = useState<SystemConfig | null>(null);
  const [configLoading, setConfigLoading] = useState(false);
  const [autoCalcLoading, setAutoCalcLoading] = useState(false);
  const [isInitialLoading, setIsInitialLoading] = useState(true);
  const [initError, setInitError] = useState<string | null>(null);
  
  // 密码管理状态
  const [isPasswordSectionExpanded, setIsPasswordSectionExpanded] = useState(false);
  const [loginPasswordForm, setLoginPasswordForm] = useState({
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
  });
  const [adminPasswordForm, setAdminPasswordForm] = useState({
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
  });
  const [passwordLoading, setPasswordLoading] = useState({
    login: false,
    admin: false
  });
  // 移除未使用的状态变量
  const [showResetSystemConfirm, setShowResetSystemConfirm] = useState(false);
  const [isResetting, setIsResetting] = useState(false);
  const [isSimulating, setIsSimulating] = useState(false);
  const [simulationResult, setSimulationResult] = useState<{
    totalDraws: number;
    results: Array<{
      prizeName: string;
      prizeLevel: number;
      count: number;
      percentage: number;
    }>;
    actualProbabilities: Record<string, number>;
  } | null>(null);
  const [showSimulationResult, setShowSimulationResult] = useState(false);

  // 防抖更新状态
  const updateDebounceTimer = useRef<NodeJS.Timeout | null>(null);
  const [stablePrizes, setStablePrizes] = useState<Prize[]>([]);

  // 优化防抖更新奖项数据，使用更高效的比较算法
  const debouncedUpdatePrizes = useCallback((newPrizes: Prize[]) => {
    // 清除之前的定时器
    if (updateDebounceTimer.current) {
      clearTimeout(updateDebounceTimer.current);
    }
    
    const timer = setTimeout(() => {
      // 使用JSON字符串比较进行快速检测
      const newPrizesStr = JSON.stringify(newPrizes);
      const currentPrizesStr = JSON.stringify(stablePrizes);
      
      if (newPrizesStr !== currentPrizesStr) {
        console.log('检测到奖项数据变化，更新稳定状态');
        setStablePrizes([...newPrizes]);
      }
      updateDebounceTimer.current = null;
    }, 300); // 增加防抖延迟到300ms，减少频繁更新
    
    updateDebounceTimer.current = timer;
  }, [stablePrizes]);

  // 页面初始化时加载数据和WebSocket连接
  useEffect(() => {
    const initializeAdminPage = async () => {
      try {
        setIsInitialLoading(true);
        setInitError(null);
        console.log('Admin页面初始化 - 开始加载数据');
        // 确保在页面刷新后立即加载奖品数据
        await Promise.all([
          loadPrizes(),
          loadSystemConfig()
        ]);
        console.log('Admin页面初始化 - 数据加载完成');
      } catch (error) {
        console.error('Admin页面初始化失败:', error);
        
        // 提供更具体的错误信息
        let errorMessage = '页面初始化失败，请刷新重试';
        if (error instanceof TypeError && error.message.includes('fetch')) {
          errorMessage = '网络连接失败，请检查网络连接或稍后重试';
        } else if (error.message?.includes('Failed to fetch')) {
          errorMessage = 'API连接失败，请确认后端服务正常运行';
        }
        
        setInitError(errorMessage);
        showError(errorMessage);
      } finally {
        setIsInitialLoading(false);
      }
    };
    
    initializeAdminPage();
    
    // WebSocket连接状态检查
    const checkConnection = () => {
      setIsWebSocketConnected(websocketService.isConnected());
    };
    
    // 立即检查一次
    checkConnection();
    
    // 定期检查连接状态
    const connectionInterval = setInterval(checkConnection, 3000); // 降低检查频率到3秒
    
    // 订阅数据更新事件
    const eventService = EventService.getInstance();// 订阅事件 - 直接使用WebSocket事件更新数据，避免重复调用loadPrizes
    const unsubscribePrizes = eventService.subscribe(EVENT_TYPES.PRIZES_UPDATED, ((event: CustomEvent) => {
      console.log('Admin页面 - 收到奖品更新事件');
      // 直接从事件中获取更新的奖品数据，避免重复API调用
      if (event.detail && event.detail.updatedPrizes) {
        const updatedPrizes = event.detail.updatedPrizes.map((dbPrize: any) => ({
          id: dbPrize.id,
          name: dbPrize.prize_name,
          level: dbPrize.prize_level,
          totalQuantity: dbPrize.total_quantity,
          remainingQuantity: dbPrize.remaining_quantity,
          probability: dbPrize.probability,
          is_active: dbPrize.is_active
        }));
        // 触发防抖更新
        debouncedUpdatePrizes(updatedPrizes);
      }
    }) as EventListener);
    
    const unsubscribeRecords = eventService.subscribe(EVENT_TYPES.RECORDS_UPDATED, () => {
      console.log('Admin页面 - 收到记录更新事件');
      // 管理页面可能需要刷新相关数据
    });

    // 监听系统配置更新事件
    const unsubscribeSystemConfig = eventService.subscribe('system_config_updated', () => {
      console.log('Admin页面 - 收到系统配置更新事件');
      loadSystemConfig();
    });

    // 监听数据清空事件
    const unsubscribeDataClear = eventService.subscribe('data_cleared', () => {
      console.log('Admin页面 - 收到数据清空事件');
      loadPrizes(); // 重新加载奖项数据
    });

    // 监听系统重置事件
    const unsubscribeSystemReset = eventService.subscribe('system_reset', () => {
      console.log('Admin页面 - 收到系统重置事件');
      loadPrizes();
      loadSystemConfig();
    });

    // 监听强制重置事件
    const unsubscribeForceReset = eventService.subscribe('force_reset', () => {
      console.log('Admin页面 - 收到强制重置事件');
      loadPrizes();
      loadSystemConfig();
    });
    
    return () => {
      clearInterval(connectionInterval);
      unsubscribePrizes();
      unsubscribeRecords();
      unsubscribeSystemConfig();
      unsubscribeDataClear();
      unsubscribeSystemReset();
      unsubscribeForceReset();
      // 清理防抖定时器
      if (updateDebounceTimer.current) {
        clearTimeout(updateDebounceTimer.current);
      }
    };
  }, []); // 空依赖数组，确保只在组件挂载时执行一次
  
  // 监听prizes变化，使用防抖更新
  useEffect(() => {
    if (prizes && prizes.length >= 0) {
      console.log('Admin页面 - prizes数据更新:', prizes.length, '个奖项');
      debouncedUpdatePrizes(prizes);
    }
  }, [prizes, debouncedUpdatePrizes]);

  // 初始化稳定奖项数据
  useEffect(() => {
    if (prizes && prizes.length > 0 && stablePrizes.length === 0) {
      setStablePrizes([...prizes]);
    }
  }, [prizes, stablePrizes.length]);
  


  const loadSystemConfig = async () => {
    try {
      const api = ApiService.getInstance();
      const config = await api.getSystemConfig();
      setSystemConfig(config);
    } catch (error) {
      console.error('加载系统配置失败:', error);
      
      // 提供更详细的错误信息
      if (error instanceof TypeError && error.message.includes('fetch')) {
        console.error('系统配置加载 - 网络连接错误，请检查后端服务是否正常运行');
      } else if (error.message?.includes('Failed to fetch')) {
        console.error('系统配置加载 - API请求失败，可能是网络问题或服务器未响应');
      }
      
      // 设置默认配置避免页面崩溃
      setSystemConfig({
        id: '1',
        admin_password: '',
        login_password: '',
        background_config: '',
        max_draw_times: 1,
        hide_positions: '3,4,5,6',
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
      });
    }
  };

  const handleUpdateSystemConfig = async (maxDrawTimes: number) => {
    setConfigLoading(true);
    try {
      const api = ApiService.getInstance();
      await api.updateSystemConfig({ max_draw_times: maxDrawTimes });
      await loadSystemConfig();
      
      // 同步更新store中的系统配置
      const updatedConfig = await api.getSystemConfig();
      useAppStore.getState().setSystemConfig(updatedConfig);
      
      showSuccess('系统配置更新成功');
    } catch (error) {
        console.error('更新系统配置失败:', error);
        showError('更新系统配置失败，请重试');
    } finally {
      setConfigLoading(false);
    }
  };

  const handleAddPrize = async () => {
    if (!formData.prize_name || !formData.prize_name.trim()) return;
    
    // 验证概率值
    if (formData.probability < 0 || formData.probability > 1) {
      showError('概率值必须在0-1之间');
      return;
    }
    
    setLoading(true);
    try {
      const api = ApiService.getInstance();
      await api.addPrize({
        prize_name: formData.prize_name,
        prize_level: formData.prize_level,
        total_quantity: formData.total_quantity,
        remaining_quantity: formData.total_quantity,
        probability: formData.probability,
        is_active: formData.is_active
      });
      
      // 不再手动调用loadPrizes，依赖WebSocket事件自动更新
      setShowAddForm(false);
      setFormData({ prize_name: '', prize_level: 1, total_quantity: 1, probability: 0.1, is_active: true });
      
      // 自动计算概率
      await handleAutoCalculateProbability();
      
      showSuccess('奖项添加成功，概率已自动重新计算！');
      
    } catch (error) {
      console.error('添加奖项失败:', error);
      showError('添加奖项失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  const handleUpdatePrize = async () => {
    if (!editingPrize || !formData.prize_name || !formData.prize_name.trim()) return;
    
    // 验证概率值
    if (formData.probability < 0 || formData.probability > 1) {
      showError('概率值必须在0-1之间');
      return;
    }
    
    setLoading(true);
    try {
      const api = ApiService.getInstance();
      await api.updatePrize(editingPrize.id, {
        prize_name: formData.prize_name,
        prize_level: formData.prize_level,
        total_quantity: formData.total_quantity,
        probability: formData.probability,
        is_active: formData.is_active
      });
      
      // 不再手动调用loadPrizes，依赖WebSocket事件自动更新
      setEditingPrize(null);
      setFormData({ prize_name: '', prize_level: 1, total_quantity: 1, probability: 0.1, is_active: true });
      
      // 自动计算概率
      await handleAutoCalculateProbability();
      
      showSuccess('奖项更新成功，概率已自动重新计算！');
      
    } catch (error) {
      console.error('更新奖项失败:', error);
      showError('更新奖项失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  const handleDeletePrize = async (prizeId: string) => {
    if (!window.confirm('确定要删除这个奖项吗？')) return;
    
    setLoading(true);
    try {
      const api = ApiService.getInstance();
      await api.deletePrize(prizeId);
      // 不再手动调用loadPrizes，依赖WebSocket事件自动更新
      showSuccess('奖项删除成功！');
    } catch (error) {
        console.error('删除奖项失败:', error);
        showError('删除奖项失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  const startEdit = (prize: Prize) => {
    setEditingPrize(prize);
    setFormData({
      prize_name: prize.name || '',
      prize_level: prize.level || 1,
      total_quantity: prize.totalQuantity || 0,
      probability: prize.probability || 0,
      is_active: prize.is_active ?? true
    });
    setShowAddForm(false);
  };

  const cancelEdit = () => {
    setEditingPrize(null);
    setShowAddForm(false);
    setFormData({ prize_name: '', prize_level: 1, total_quantity: 1, probability: 0.1, is_active: true });
  };

  // 自动计算概率
  const handleAutoCalculateProbability = async () => {
    setAutoCalcLoading(true);
    try {
      const api = ApiService.getInstance();
      const allPrizes = await api.getAllPrizes();
      
      if (allPrizes.length === 0) {
        showWarning('没有奖项可以计算概率');
        return;
      }

      // 只对启用的奖项进行概率计算
      const enabledPrizes = allPrizes.filter(prize => prize.is_active);
      
      if (enabledPrizes.length === 0) {
        showWarning('没有启用的奖项可以计算概率');
        return;
      }

      // 计算启用奖项的总数量
      const totalQuantity = enabledPrizes.reduce((sum, prize) => sum + prize.total_quantity, 0);
      
      if (totalQuantity === 0) {
        showWarning('启用奖项数量总和为0，无法计算概率');
        return;
      }

      // 为所有奖项设置概率
      for (const prize of allPrizes) {
        if (prize.is_active) {
          // 启用的奖项按数量比例分配概率
          const probability = prize.total_quantity / totalQuantity;
          const finalProbability = Math.max(0.0001, Math.min(probability, 1));
          await api.updatePrize(prize.id, { probability: finalProbability });
        } else {
          // 未启用的奖项概率设为0
          await api.updatePrize(prize.id, { probability: 0 });
        }
      }
      
      // 重新加载奖项数据
      await loadPrizes();
      showSuccess('概率自动计算完成！');
      
    } catch (error) {
      console.error('自动计算概率失败:', error);
      showError('自动计算概率失败，请重试');
    } finally {
      setAutoCalcLoading(false);
    }
  };

  // 验证概率总和
  const validateTotalProbability = () => {
    // 只验证启用奖项的概率总和
    const enabledPrizes = prizes.filter(prize => prize.is_active);
    const totalProb = enabledPrizes.reduce((sum, prize) => {
      const probability = isNaN(prize.probability) ? 0 : prize.probability;
      return sum + probability;
    }, 0);
    return { 
      total: isNaN(totalProb) ? 0 : totalProb, 
      isValid: enabledPrizes.length === 0 || Math.abs(totalProb - 1) < 0.01,
      enabledCount: enabledPrizes.length
    };
  };

  // 密码强度验证
  const validatePassword = (password: string) => {
    if (password.length < 6) {
      return { isValid: false, message: '密码长度至少6位' };
    }
    if (password.length > 20) {
      return { isValid: false, message: '密码长度不能超过20位' };
    }
    return { isValid: true, message: '' };
  };

  // 更新首页登录密码
  const handleUpdateLoginPassword = async () => {
    const { currentPassword, newPassword, confirmPassword } = loginPasswordForm;
    
    if (!currentPassword || !newPassword || !confirmPassword) {
      showError('请填写所有密码字段');
      return;
    }
    
    if (newPassword !== confirmPassword) {
      showError('新密码和确认密码不一致');
      return;
    }
    
    const validation = validatePassword(newPassword);
    if (!validation.isValid) {
      showError(validation.message);
      return;
    }
    
    setPasswordLoading({ ...passwordLoading, login: true });
    
    try {
      console.log('开始更新首页登录密码...');
      
      // 验证当前首页登录密码
      const api = ApiService.getInstance();
      console.log('验证当前首页登录密码:', currentPassword);
      const isCurrentValid = await api.validateLoginPassword(currentPassword);
      console.log('当前首页登录密码验证结果:', isCurrentValid);
      
      if (!isCurrentValid) {
        showError('当前首页登录密码错误');
        return;
      }
 
      // 更新首页登录密码
      console.log('开始更新首页登录密码到:', newPassword);
      const updateSuccess = await api.updateLoginPassword(newPassword);
      console.log('首页登录密码更新结果:', updateSuccess);
      
      if (!updateSuccess) {
        throw new Error('首页登录密码更新失败');
      }
      
      // 清空表单
      setLoginPasswordForm({
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
      });
      
      console.log('首页登录密码更新成功');
      showSuccess('首页登录密码更新成功');
    } catch (error) {
      console.error('更新首页登录密码失败:', error);
      showError(`更新首页登录密码失败: ${error.message || '请重试'}`);
    } finally {
      setPasswordLoading({ ...passwordLoading, login: false });
    }
  };

  // 更新后台管理密码
  const handleUpdateAdminPassword = async () => {
    const { currentPassword, newPassword, confirmPassword } = adminPasswordForm;
    
    if (!currentPassword || !newPassword || !confirmPassword) {
      showError('请填写所有密码字段');
      return;
    }
    
    if (newPassword !== confirmPassword) {
      showError('新密码和确认密码不一致');
      return;
    }
    
    const validation = validatePassword(newPassword);
    if (!validation.isValid) {
      showError(validation.message);
      return;
    }
    
    setPasswordLoading({ ...passwordLoading, admin: true });
    
    try {
      console.log('开始更新后台管理密码...');
      
      // 验证当前密码
      const api = ApiService.getInstance();
      console.log('验证当前密码:', currentPassword);
      const isCurrentValid = await api.validateCurrentAdminPassword(currentPassword);
      console.log('当前密码验证结果:', isCurrentValid);
      
      if (!isCurrentValid) {
        showError('当前密码错误');
        return;
      }
 
      // 更新密码
      console.log('开始更新密码到:', newPassword);
      const updateSuccess = await api.updateAdminPassword(newPassword);
      console.log('密码更新结果:', updateSuccess);
      
      if (!updateSuccess) {
        throw new Error('密码更新失败');
      }
      
      // 清空表单
      setAdminPasswordForm({
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
      });
      
      console.log('后台管理密码更新成功');
      showSuccess('后台管理密码更新成功');
    } catch (error) {
      console.error('更新后台密码失败:', error);
      showError(`更新密码失败: ${error.message || '请重试'}`);
    } finally {
       setPasswordLoading({ ...passwordLoading, admin: false });
     }
   };

  // 重置后台管理密码为默认值
  const handleResetAdminPasswordToDefault = async () => {
    if (!window.confirm('确定要将后台管理密码重置为默认值 "123456" 吗？')) {
      return;
    }
    
    setPasswordLoading({ ...passwordLoading, admin: true });
    
    try {
      console.log('开始重置后台管理密码为默认值...');
      const api = ApiService.getInstance();
      const resetSuccess = await api.resetAdminPasswordToDefault();
      
      if (resetSuccess) {
        console.log('后台管理密码重置成功');
        showSuccess('后台管理密码已重置为默认值 "123456"');
        
        // 清空表单
        setAdminPasswordForm({
          currentPassword: '',
          newPassword: '',
          confirmPassword: ''
        });
      } else {
        throw new Error('后台管理密码重置失败');
      }
    } catch (error) {
      console.error('重置后台管理密码失败:', error);
      showError(`重置后台管理密码失败: ${error.message || '请重试'}`);
    } finally {
      setPasswordLoading({ ...passwordLoading, admin: false });
    }
  };

  // 重置首页登录密码为默认值
  const handleResetLoginPasswordToDefault = async () => {
    if (!window.confirm('确定要将首页登录密码重置为默认值 "123456" 吗？')) {
      return;
    }
    
    setPasswordLoading({ ...passwordLoading, login: true });
    
    try {
      console.log('开始重置首页登录密码为默认值...');
      const api = ApiService.getInstance();
      const resetSuccess = await api.resetLoginPasswordToDefault();
      
      if (resetSuccess) {
        console.log('首页登录密码重置成功');
        showSuccess('首页登录密码已重置为默认值 "123456"');
        
        // 清空表单
        setLoginPasswordForm({
          currentPassword: '',
          newPassword: '',
          confirmPassword: ''
        });
      } else {
        throw new Error('首页登录密码重置失败');
      }
    } catch (error) {
      console.error('重置首页登录密码失败:', error);
      showError(`重置首页登录密码失败: ${error.message || '请重试'}`);
    } finally {
      setPasswordLoading({ ...passwordLoading, login: false });
    }
  };

  // 强制重置数据库
  const handleForceResetDatabase = async () => {
    if (!window.confirm('确定要强制重置数据库吗？\n\n此操作将：\n• 完全删除IndexedDB数据库\n• 重新初始化所有数据\n• 密码将重置为123456\n\n⚠️ 此操作不可逆！')) {
      return;
    }
    
    setIsResetting(true);
    try {
      console.log('开始强制重置数据库...');
      const api = ApiService.getInstance();
      const success = await api.forceResetDatabase();
      
      if (success) {
        showSuccess('数据库强制重置成功！\n\n所有密码已重置为：123456\n请刷新页面以应用更改');
        // 延迟刷新页面以确保用户看到成功消息
        setTimeout(() => {
          window.location.reload();
        }, 2000);
      } else {
        showError('数据库重置失败，请重试');
      }
    } catch (error) {
      console.error('强制重置数据库失败:', error);
      showError(`数据库重置失败: ${error.message || '请重试'}`);
    } finally {
      setIsResetting(false);
    }
  };

  // 一键重置系统
  const handleResetSystem = async () => {
    setIsResetting(true);
    try {
      const api = ApiService.getInstance();
      const success = await api.resetSystemCompletely();
      if (success) {
        showSuccess('系统重置成功！\n\n已完成：\n• 清空所有抽奖记录\n• 重置奖项剩余数量\n• 重新计算中奖概率\n• 清空学生抽奖数据');
        setShowResetSystemConfirm(false);
        // 刷新页面数据
        await loadPrizes();
        await loadSystemConfig();
      } else {
        showError('系统重置失败，请重试');
      }
    } catch (error) {
      console.error('系统重置失败:', error);
      showError(`系统重置失败: ${error.message || '请重试'}`);
    } finally {
      setIsResetting(false);
    }
  };

  // 模拟500次抽奖
  const handleSimulateLottery = async () => {
    setIsSimulating(true);
    try {
      console.log('开始模拟500次抽奖...');
      const api = ApiService.getInstance();
      const result = await api.simulateLottery(500);
      
      console.log('模拟抽奖结果:', result);
      setSimulationResult(result);
      setShowSimulationResult(true);
      
    } catch (error) {
      console.error('模拟抽奖失败:', error);
      showError(`模拟抽奖失败: ${error.message || '请重试'}`);
    } finally {
      setIsSimulating(false);
    }
  };

  // 初始加载状态
  if (isInitialLoading) {
    return (
      <div className="min-h-screen bg-gray-900">
        <LoadingSpinner size="lg" text="正在加载管理面板..." fullScreen />
      </div>
    );
  }

  // 初始化错误状态
  if (initError) {
    return (
      <div className="min-h-screen bg-gray-900 p-6">
        <div className="max-w-4xl mx-auto">
          <Empty
            title="加载失败"
            description={initError}
            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-gray-900">
      {/* 头部 */}
      <div className="bg-gray-800 shadow-sm border-b border-gray-700">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center h-16">
            <div className="flex items-center gap-4">
              <button
                onClick={() => navigate('/')}
                className="flex items-center gap-2 px-3 py-2 text-gray-300 hover:text-gray-100 transition-colors rounded-lg hover:bg-gray-700"
              >
                <ArrowLeft size={20} />
                返回首页
              </button>
              <h1 className="text-2xl font-bold text-gray-100">后台管理</h1>
              <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={`text-sm ${isWebSocketConnected ? 'text-green-400' : 'text-red-400'}`}>
                  {isWebSocketConnected ? '实时连接' : '连接断开'}
                </span>
              </div>
            </div>
            <div className="flex items-center gap-4">

              <button
                onClick={() => setShowResetSystemConfirm(true)}
                className="flex items-center gap-2 px-4 py-2 text-red-400 hover:text-red-300 transition-colors"
              >
                <Settings size={20} />
                一键重置
              </button>
              <button
                onClick={handleForceResetDatabase}
                className="flex items-center gap-2 px-4 py-2 text-orange-400 hover:text-orange-300 transition-colors"
              >
                <Database size={20} />
                强制重置数据库
              </button>
              <button
                 onClick={handleSimulateLottery}
                 disabled={isSimulating}
                 className="flex items-center gap-2 px-4 py-2 text-purple-400 hover:text-purple-300 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
               >
                 <Zap size={20} />
                 {isSimulating ? '模拟中...' : '模拟500次抽奖'}
               </button>
              <button
                onClick={() => {
                  // 使用AuthService进行登出
                  const authService = AuthService.getInstance();
                  authService.logout();
                  // 调用store的logout方法更新状态
                  logout();
                  console.log('已退出登录，JWT token已清除');
                }}
                className="flex items-center gap-2 px-4 py-2 text-gray-300 hover:text-gray-100 transition-colors"
              >
                <LogOut size={20} />
                退出登录
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* 主要内容 */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* 系统配置 */}
        <div className="bg-gray-800 rounded-lg shadow border border-gray-700 mb-8">
          <div className="px-6 py-4 border-b border-gray-700">
            <div className="flex items-center gap-2">
              <Settings size={20} className="text-gray-300" />
              <h2 className="text-lg font-semibold text-gray-100">系统配置</h2>
            </div>
          </div>
          <div className="p-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">
                  抽奖次数上限
                </label>
                <div className="flex items-center gap-4">
                  <input
                    type="number"
                    min="1"
                    max="10"
                    value={systemConfig?.max_draw_times || 1}
                    onChange={(e) => {
                      const value = parseInt(e.target.value) || 1;
                      handleUpdateSystemConfig(value);
                    }}
                    className="w-32 px-3 py-2 border border-gray-600 bg-gray-700 text-gray-100 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    disabled={configLoading}
                  />
                  <span className="text-sm text-gray-400">
                    每个学号最多可抽奖 {systemConfig?.max_draw_times || 1} 次
                  </span>
                  {configLoading && (
                    <span className="text-sm text-blue-400">更新中...</span>
                  )}
                </div>
                <p className="text-xs text-gray-500 mt-2">
                  设置每个学号的最大抽奖次数，范围：1-10次
                </p>
              </div>
            </div>
          </div>
        </div>

        {/* 密码管理 */}
        <div className="bg-gray-800 rounded-lg shadow border border-gray-700 mb-8">
          <div className="px-6 py-4 border-b border-gray-700">
            <div 
              className="flex items-center justify-between cursor-pointer hover:bg-gray-700 rounded-lg px-2 py-1 transition-colors"
              onClick={() => setIsPasswordSectionExpanded(!isPasswordSectionExpanded)}
            >
              <div className="flex items-center gap-2">
                <Settings size={20} className="text-gray-300" />
                <h2 className="text-lg font-semibold text-gray-100">密码管理</h2>
              </div>
              <div className="flex items-center gap-2">
                <span className="text-sm text-gray-400">
                  {isPasswordSectionExpanded ? '收起' : '展开'}
                </span>
                {isPasswordSectionExpanded ? (
                  <ChevronUp size={20} className="text-gray-400" />
                ) : (
                  <ChevronDown size={20} className="text-gray-400" />
                )}
              </div>
            </div>
          </div>
          {isPasswordSectionExpanded && (
            <div className="p-6 transition-all duration-300 ease-in-out">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                {/* 首页登录密码 */}
                <div className="bg-gray-700 rounded-lg p-4">
                  <h3 className="text-md font-semibold text-gray-100 mb-4">首页登录密码</h3>
                  <div className="space-y-3">
                  <div>
                    <label className="block text-sm font-medium text-gray-300 mb-2">
                      当前密码
                    </label>
                    <input
                      type="password"
                      value={loginPasswordForm.currentPassword}
                      onChange={(e) => setLoginPasswordForm({...loginPasswordForm, currentPassword: e.target.value})}
                      className="w-full px-3 py-2 border border-gray-600 bg-gray-800 text-gray-100 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                      placeholder="请输入当前密码"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-300 mb-2">
                      新密码
                    </label>
                    <input
                      type="password"
                      value={loginPasswordForm.newPassword}
                      onChange={(e) => setLoginPasswordForm({...loginPasswordForm, newPassword: e.target.value})}
                      className="w-full px-3 py-2 border border-gray-600 bg-gray-800 text-gray-100 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                      placeholder="请输入新密码"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-300 mb-2">
                      确认新密码
                    </label>
                    <input
                      type="password"
                      value={loginPasswordForm.confirmPassword}
                      onChange={(e) => setLoginPasswordForm({...loginPasswordForm, confirmPassword: e.target.value})}
                      className="w-full px-3 py-2 border border-gray-600 bg-gray-800 text-gray-100 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                      placeholder="请再次输入新密码"
                    />
                  </div>
                  <div className="space-y-2">
                    <button
                      onClick={handleUpdateLoginPassword}
                      disabled={passwordLoading.login}
                      className="w-full px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                    >
                      {passwordLoading.login ? '更新中...' : '更新首页密码'}
                    </button>
                    <button
                      onClick={handleResetLoginPasswordToDefault}
                      disabled={passwordLoading.login}
                      className="w-full px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors text-sm"
                    >
                      {passwordLoading.login ? '重置中...' : '重置为默认密码 (admin123)'}
                    </button>
                  </div>
                </div>
              </div>

                {/* 后台管理密码 */}
                <div className="bg-gray-700 rounded-lg p-4">
                <h3 className="text-md font-semibold text-gray-100 mb-4">后台管理密码</h3>
                <div className="space-y-3">
                  <div>
                    <label className="block text-sm font-medium text-gray-300 mb-2">
                      当前密码
                    </label>
                    <input
                      type="password"
                      value={adminPasswordForm.currentPassword}
                      onChange={(e) => setAdminPasswordForm({...adminPasswordForm, currentPassword: e.target.value})}
                      className="w-full px-3 py-2 border border-gray-600 bg-gray-800 text-gray-100 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                      placeholder="请输入当前密码"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-300 mb-2">
                      新密码
                    </label>
                    <input
                      type="password"
                      value={adminPasswordForm.newPassword}
                      onChange={(e) => setAdminPasswordForm({...adminPasswordForm, newPassword: e.target.value})}
                      className="w-full px-3 py-2 border border-gray-600 bg-gray-800 text-gray-100 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                      placeholder="请输入新密码"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-300 mb-2">
                      确认新密码
                    </label>
                    <input
                      type="password"
                      value={adminPasswordForm.confirmPassword}
                      onChange={(e) => setAdminPasswordForm({...adminPasswordForm, confirmPassword: e.target.value})}
                      className="w-full px-3 py-2 border border-gray-600 bg-gray-800 text-gray-100 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                      placeholder="请再次输入新密码"
                    />
                  </div>
                  <div className="space-y-2">
                    <button
                      onClick={handleUpdateAdminPassword}
                      disabled={passwordLoading.admin}
                      className="w-full px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                    >
                      {passwordLoading.admin ? '更新中...' : '更新后台密码'}
                    </button>
                    <button
                      onClick={handleResetAdminPasswordToDefault}
                      disabled={passwordLoading.admin}
                      className="w-full px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors text-sm"
                    >
                      {passwordLoading.admin ? '重置中...' : '重置为默认密码 (admin123)'}
                    </button>
                  </div>
                </div>
                </div>
              </div>
            </div>
          )}
        </div>

        {/* 奖项管理 */}
        <div className="bg-gray-800 rounded-lg shadow border border-gray-700">
          <div className="px-6 py-4 border-b border-gray-700">
            <div className="flex justify-between items-center mb-4">
              <h2 className="text-lg font-semibold text-gray-100">奖项配置</h2>
              <div className="flex gap-2">
                <button
                  onClick={handleAutoCalculateProbability}
                  disabled={autoCalcLoading || prizes.length === 0}
                  className="flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                >
                  <Settings size={20} />
                  {autoCalcLoading ? '计算中...' : '自动计算概率'}
                </button>
                <button
                  onClick={() => {
                    setShowAddForm(true);
                    setEditingPrize(null);
                    setFormData({ prize_name: '', prize_level: 1, total_quantity: 1, probability: 0.1, is_active: true });
                  }}
                  className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                >
                  <Plus size={20} />
                  添加奖项
                </button>
              </div>
            </div>
            
            {/* 概率验证显示 */}
            {prizes.length > 0 && (() => {
              const probValidation = validateTotalProbability();
              return (
                <div className={`p-3 rounded-lg border ${
                  probValidation.isValid 
                    ? 'bg-green-900/20 border-green-600 text-green-300' 
                    : 'bg-red-900/20 border-red-600 text-red-300'
                }`}>
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium">
                      概率总和: {(isNaN(probValidation.total) ? 0 : probValidation.total * 1000).toFixed(2)}‰
                    </span>
                    <span className={`text-xs px-2 py-1 rounded ${
                      probValidation.isValid 
                        ? 'bg-green-600 text-white' 
                        : 'bg-red-600 text-white'
                    }`}>
                      {probValidation.isValid ? '✓ 正常' : '⚠ 异常'}
                    </span>
                  </div>
                  {!probValidation.isValid && (
                    <p className="text-xs mt-1 opacity-80">
                      建议使用"自动计算概率"功能重新分配概率
                    </p>
                  )}
                </div>
              );
            })()}
          </div>

          <div className="p-6">
            {/* 添加/编辑表单 */}
            {(showAddForm || editingPrize) && (
              <div className="mb-6 p-4 bg-gray-700 rounded-lg border border-gray-600">
                <h3 className="text-md font-semibold mb-4 text-gray-100">
                  {editingPrize ? '编辑奖项' : '添加新奖项'}
                </h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-300 mb-2">
                      奖项名称
                    </label>
                    <input
                      type="text"
                      value={formData.prize_name || ''}
                      onChange={(e) => setFormData({ ...formData, prize_name: e.target.value })}
                      className="w-full px-3 py-2 border border-gray-600 bg-gray-800 text-gray-100 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                      placeholder="请输入奖项名称"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-300 mb-2">
                      奖项等级
                    </label>
                    <input
                      type="number"
                      min="1"
                      value={formData.prize_level || 1}
                      onChange={(e) => setFormData({ ...formData, prize_level: parseInt(e.target.value) || 1 })}
                      className="w-full px-3 py-2 border border-gray-600 bg-gray-800 text-gray-100 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-300 mb-2">
                      奖品数量
                    </label>
                    <input
                      type="number"
                      min="1"
                      value={formData.total_quantity || 1}
                      onChange={(e) => setFormData({ ...formData, total_quantity: parseInt(e.target.value) || 1 })}
                      className="w-full px-3 py-2 border border-gray-600 bg-gray-800 text-gray-100 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-300 mb-2">
                      中奖概率 (千分之x)
                    </label>
                    <input
                      type="number"
                      min="0"
                      max="1"
                      step="0.01"
                      value={formData.probability || 0}
                      onChange={(e) => setFormData({ ...formData, probability: parseFloat(e.target.value) || 0 })}
                      className="w-full px-3 py-2 border border-gray-600 bg-gray-800 text-gray-100 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-300 mb-2">
                      是否启用
                    </label>
                    <select
                      value={formData.is_active !== undefined ? (formData.is_active ? 'true' : 'false') : 'true'}
                      onChange={(e) => setFormData({ ...formData, is_active: e.target.value === 'true' })}
                      className="w-full px-3 py-2 border border-gray-600 bg-gray-800 text-gray-100 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    >
                      <option value="true">启用</option>
                      <option value="false">禁用</option>
                    </select>
                  </div>
                </div>
                <div className="flex gap-2 mt-4">
                  <button
                    onClick={editingPrize ? handleUpdatePrize : handleAddPrize}
                    disabled={loading || !formData.prize_name || !formData.prize_name.trim()}
                    className="flex items-center gap-2 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                  >
                    <Save size={16} />
                    {loading ? '保存中...' : '保存'}
                  </button>
                  <button
                    onClick={cancelEdit}
                    className="flex items-center gap-2 px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors"
                  >
                    <X size={16} />
                    取消
                  </button>
                </div>
              </div>
            )}

            {/* 奖项列表 */}
            <div className="overflow-x-auto">
              <table className="min-w-full divide-y divide-gray-600">
                <thead className="bg-gray-700">
                  <tr>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase tracking-wider">
                      奖项名称
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      等级
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      总数量
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      剩余数量
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      中奖概率
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      状态
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      操作
                    </th>
                  </tr>
                </thead>
                <tbody className="bg-gray-800 divide-y divide-gray-700">
                  {(stablePrizes.length > 0 ? stablePrizes : prizes || []).map((prize, index) => {
                    // 使用稳定的key值，结合id、index和remainingQuantity确保唯一性和稳定性
                    const stableKey = `prize-${prize.id}-${index}-${prize.remainingQuantity || 0}`;
                    return (
                      <tr key={stableKey}>
                        <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-100">
                          {prize.name}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-300">
                          {prize.level || 0}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                          {prize.totalQuantity || 0}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                          {/* 使用稳定的数据显示，避免0和实际值之间跳动 */}
                          <span className="font-medium tabular-nums">
                            {typeof prize.remainingQuantity === 'number' ? prize.remainingQuantity : 0}
                          </span>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                          {(isNaN(prize.probability) ? 0 : prize.probability * 1000).toFixed(1)}‰
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-300">
                          <span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
                            prize.is_active ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                          }`}>
                            {prize.is_active ? '启用' : '禁用'}
                          </span>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                          <div className="flex gap-2">
                            <button
                              onClick={() => startEdit(prize)}
                              className="text-blue-600 hover:text-blue-900 transition-colors"
                            >
                              <Edit size={16} />
                            </button>
                            <button
                              onClick={() => handleDeletePrize(prize.id)}
                              className="text-red-600 hover:text-red-900 transition-colors"
                            >
                              <Trash2 size={16} />
                            </button>
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
              {prizes.length === 0 && (
                <div className="py-8">
                  <Empty
                    title="暂无奖项"
                    description="还没有配置任何奖项，请添加第一个奖项开始使用"
                    action={
                      <button
                        onClick={() => {
                          setShowAddForm(true);
                          setEditingPrize(null);
                        }}
                        className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
                      >
                        <Plus size={16} />
                        添加奖项
                      </button>
                    }
                  />
                </div>
              )}
            </div>
          </div>
        </div>

        {/* 模拟抽奖结果对话框 */}
        {showSimulationResult && simulationResult && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
            <div className="bg-gradient-to-br from-gray-800/95 to-gray-900/95 rounded-3xl p-8 max-w-2xl w-full mx-4 border-2 border-gray-600/50 shadow-2xl shadow-black/40 backdrop-blur-md max-h-[80vh] overflow-y-auto relative before:content-[''] before:absolute before:top-[-12px] before:left-1/2 before:transform before:-translate-x-1/2 before:w-6 before:h-6 before:rotate-45 before:bg-gradient-to-br before:from-gray-800/95 before:to-gray-900/95 before:border-l-2 before:border-t-2 before:border-gray-600/50">
              <div className="flex justify-between items-center mb-4">
                <h3 className="text-lg font-semibold text-gray-100">模拟抽奖结果</h3>
                <button
                  onClick={() => setShowSimulationResult(false)}
                  className="text-gray-400 hover:text-gray-200 transition-colors"
                >
                  <X size={20} />
                </button>
              </div>
              
              <div className="space-y-4">
                <div className="bg-gray-700 rounded-lg p-4">
                  <h4 className="text-md font-medium text-gray-200 mb-3">统计信息</h4>
                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div>
                      <span className="text-gray-400">总抽奖次数：</span>
                      <span className="text-gray-200">{simulationResult?.totalDraws || 0}</span>
                    </div>
                    <div>
                      <span className="text-gray-400">中奖次数：</span>
                      <span className="text-green-400">{simulationResult?.results?.reduce((sum, item) => sum + (item.count || 0), 0) || 0}</span>
                    </div>
                    <div>
                      <span className="text-gray-400">未中奖次数：</span>
                      <span className="text-red-400">{(simulationResult?.totalDraws || 0) - (simulationResult?.results?.reduce((sum, item) => sum + (item.count || 0), 0) || 0)}</span>
                    </div>
                    <div>
                      <span className="text-gray-400">总中奖率：</span>
                      <span className="text-blue-400">{simulationResult?.totalDraws && simulationResult.totalDraws > 0 ? (((simulationResult.results?.reduce((sum, item) => sum + (item.count || 0), 0) || 0) / simulationResult.totalDraws) * 100).toFixed(2) : '0.00'}%</span>
                    </div>
                  </div>
                </div>
                
                <div className="bg-gray-700 rounded-lg p-4">
                   <h4 className="text-md font-medium text-gray-200 mb-3">各奖项中奖情况</h4>
                   <div className="space-y-3">
                     {(simulationResult?.results || []).map((stat, index) => (
                       <div key={index} className="bg-gray-600 rounded-lg p-3 border-l-4 border-purple-500">
                         <div className="flex justify-between items-start mb-2">
                           <h5 className="text-lg font-semibold text-white">{stat.prizeName} (等级{stat.prizeLevel})</h5>
                           <div className="text-right">
                             <div className="text-2xl font-bold text-green-400">
                               {stat.count || 0}
                             </div>
                             <div className="text-xs text-gray-400">中奖次数</div>
                           </div>
                         </div>
                         <div className="grid grid-cols-2 gap-4 text-sm">
                           <div>
                             <span className="text-gray-400">实际概率：</span>
                             <span className="text-blue-400 font-medium">
                               {stat.percentage || '0.00'}%
                             </span>
                           </div>
                           <div>
                             <span className="text-gray-400">设定概率：</span>
                             <span className="text-yellow-400 font-medium">
                               {simulationResult?.actualProbabilities?.[stat.prizeName] || '0.00'}%
                             </span>
                           </div>
                         </div>
                         <div className="mt-2">
                           <div className="w-full bg-gray-700 rounded-full h-2">
                             <div 
                               className="bg-gradient-to-r from-purple-500 to-blue-500 h-2 rounded-full transition-all duration-300"
                               style={{ width: `${isNaN(Number(stat.percentage)) ? 0 : Number(stat.percentage)}%` }}
                             ></div>
                           </div>
                         </div>
                       </div>
                     ))}
                   </div>
                 </div>
              </div>
              
              <div className="mt-6 flex justify-end">
                <button
                  onClick={() => setShowSimulationResult(false)}
                  className="px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors"
                >
                  关闭
                </button>
              </div>
            </div>
          </div>
        )}

        {/* 一键重置系统确认对话框 */}
        {showResetSystemConfirm && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
            <div className="bg-gradient-to-br from-gray-800/95 to-gray-900/95 rounded-3xl p-8 max-w-md w-full mx-4 border-2 border-gray-600/50 shadow-2xl shadow-black/40 backdrop-blur-md relative before:content-[''] before:absolute before:top-[-12px] before:left-1/2 before:transform before:-translate-x-1/2 before:w-6 before:h-6 before:rotate-45 before:bg-gradient-to-br before:from-gray-800/95 before:to-gray-900/95 before:border-l-2 before:border-t-2 before:border-gray-600/50">
              <h3 className="text-lg font-semibold text-gray-100 mb-4">确认一键重置系统</h3>
              <div className="text-gray-300 mb-6">
                <p className="mb-3">此操作将会：</p>
                <ul className="list-disc list-inside space-y-1 text-sm text-gray-400">
                  <li>清空所有抽奖记录</li>
                  <li>重置所有奖项的剩余数量</li>
                  <li>重新计算中奖概率</li>
                  <li>清空所有学生的抽奖数据</li>
                </ul>
                <p className="mt-3 text-red-400 font-medium">⚠️ 此操作不可逆，请谨慎操作！</p>
              </div>
              <div className="flex gap-3">
                <button
                  onClick={handleResetSystem}
                  disabled={isResetting}
                  className="flex-1 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                >
                  {isResetting ? '重置中...' : '确认重置'}
                </button>
                <button
                  onClick={() => setShowResetSystemConfirm(false)}
                  disabled={isResetting}
                  className="flex-1 px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                >
                  取消
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default Admin;