import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { ArrowLeft, Trash2, RefreshCw, CheckCircle } from 'lucide-react';
import ApiService from "../services/apiService";
import { useToast } from '../hooks/useToast';

const ClearRecords: React.FC = () => {
  const navigate = useNavigate();
  const { showSuccess, showError, showWarning } = useToast();
  const [isClearing, setIsClearing] = useState(false);
  const [clearResult, setClearResult] = useState<string | null>(null);
  const [currentData, setCurrentData] = useState<any>(null);

  const api = ApiService.getInstance();

  const checkCurrentData = async () => {
    try {
      const records = await api.getLotteryRecords();
      const prizes = await api.getAllPrizes();
      const students = JSON.parse(localStorage.getItem('lottery_students') || '[]');
      
      setCurrentData({
        recordsCount: records.length,
        studentsCount: students.length,
        prizes: prizes.map(p => ({
          name: p.prize_name,
          total: p.total_quantity,
          remaining: p.remaining_quantity
        }))
      });
    } catch (error) {
      console.error('ClearRecords页面 - 获取当前数据失败:', error);
      showError('获取数据失败，请检查网络连接');
      setCurrentData({
        recordsCount: 0,
        studentsCount: 0,
        prizes: []
      });
    }
  };

  const handleClearRecords = async () => {
    if (!window.confirm('确定要清空所有抽奖记录吗？此操作不可撤销！')) {
      return;
    }

    setIsClearing(true);
    setClearResult(null);

    try {
      const success = await api.clearAllLotteryRecords();
      
      if (success) {
        setClearResult('✅ 抽奖记录清空成功！');
        // 重新检查数据
        setTimeout(async () => {
          await checkCurrentData();
        }, 500);
      } else {
        setClearResult('❌ 清空操作失败，请重试');
      }
    } catch (error) {
      setClearResult(`❌ 清空操作出错: ${error}`);
    } finally {
      setIsClearing(false);
    }
  };

  React.useEffect(() => {
    checkCurrentData();
  }, []);

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 p-4">
      <div className="max-w-4xl mx-auto">
        {/* 头部 */}
        <div className="bg-white rounded-lg shadow-lg p-6 mb-6">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <button
                onClick={() => navigate('/admin')}
                className="flex items-center space-x-2 text-gray-600 hover:text-gray-800 transition-colors"
              >
                <ArrowLeft className="w-5 h-5" />
                <span>返回管理</span>
              </button>
              <h1 className="text-2xl font-bold text-gray-800">清空抽奖记录</h1>
            </div>
          </div>
        </div>

        {/* 当前数据状态 */}
        <div className="bg-white rounded-lg shadow-lg p-6 mb-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-xl font-semibold text-gray-800">当前数据状态</h2>
            <button
              onClick={checkCurrentData}
              className="flex items-center space-x-2 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
            >
              <RefreshCw className="w-4 h-4" />
              <span>刷新数据</span>
            </button>
          </div>

          {currentData && (
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              <div className="bg-blue-50 p-4 rounded-lg">
                <h3 className="font-semibold text-blue-800 mb-2">抽奖记录</h3>
                <p className="text-2xl font-bold text-blue-600">{currentData.recordsCount}</p>
                <p className="text-sm text-blue-600">条记录</p>
              </div>
              
              <div className="bg-green-50 p-4 rounded-lg">
                <h3 className="font-semibold text-green-800 mb-2">学生记录</h3>
                <p className="text-2xl font-bold text-green-600">{currentData.studentsCount}</p>
                <p className="text-sm text-green-600">个学生</p>
              </div>
              
              <div className="bg-purple-50 p-4 rounded-lg">
                <h3 className="font-semibold text-purple-800 mb-2">奖品状态</h3>
                <div className="space-y-1">
                  {currentData.prizes.map((prize: any, index: number) => (
                    <div key={index} className="text-sm">
                      <span className="text-purple-700">{prize.name}:</span>
                      <span className="text-purple-600 ml-1">
                        {prize.remaining}/{prize.total}
                      </span>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}
        </div>

        {/* 清空操作 */}
        <div className="bg-white rounded-lg shadow-lg p-6">
          <h2 className="text-xl font-semibold text-gray-800 mb-4">清空操作</h2>
          
          <div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-6">
            <h3 className="font-semibold text-red-800 mb-2">⚠️ 警告</h3>
            <p className="text-red-700 mb-2">此操作将会：</p>
            <ul className="list-disc list-inside text-red-700 space-y-1">
              <li>删除所有抽奖记录</li>
              <li>重置所有学生的抽奖次数</li>
              <li>恢复所有奖品的剩余数量到初始值</li>
            </ul>
            <p className="text-red-800 font-semibold mt-2">此操作不可恢复，请谨慎操作！</p>
          </div>

          <div className="flex items-center space-x-4">
            <button
              onClick={handleClearRecords}
              disabled={isClearing}
              className="flex items-center space-x-2 px-6 py-3 bg-red-500 text-white rounded-lg hover:bg-red-600 disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors"
            >
              {isClearing ? (
                <RefreshCw className="w-5 h-5 animate-spin" />
              ) : (
                <Trash2 className="w-5 h-5" />
              )}
              <span>{isClearing ? '清空中...' : '清空所有记录'}</span>
            </button>
          </div>

          {clearResult && (
            <div className={`mt-4 p-4 rounded-lg ${
              clearResult.includes('✅') 
                ? 'bg-green-50 border border-green-200 text-green-800'
                : 'bg-red-50 border border-red-200 text-red-800'
            }`}>
              <div className="flex items-center space-x-2">
                <CheckCircle className="w-5 h-5" />
                <span>{clearResult}</span>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default ClearRecords;