import React, { useState, useEffect } from 'react';
import DatabaseService from '../database/database';
import { Prize, Student, DrawRecord, SystemConfig } from '../types';
import { PrizeConfig } from '../database/database';

interface TestResult {
  operation: string;
  success: boolean;
  message: string;
  data?: any;
}

const CrudTest: React.FC = () => {
  const [testResults, setTestResults] = useState<TestResult[]>([]);
  const [isRunning, setIsRunning] = useState(false);
  const [dbService, setDbService] = useState<DatabaseService | null>(null);

  useEffect(() => {
    const initDb = async () => {
      try {
        const service = DatabaseService.getInstance();
        // 使用公共方法ensureInitialized替代私有方法initDatabase
        // 不再需要初始化本地数据库
        setDbService(service);
        addResult('数据库初始化', true, '数据库服务初始化成功');
      } catch (error) {
        addResult('数据库初始化', false, `初始化失败: ${error}`);
      }
    };
    initDb();
  }, []);

  const addResult = (operation: string, success: boolean, message: string, data?: any) => {
    setTestResults(prev => [...prev, { operation, success, message, data }]);
  };

  const clearResults = () => {
    setTestResults([]);
  };

  const runAllTests = async () => {
    if (!dbService) {
      addResult('测试准备', false, '数据库服务未初始化');
      return;
    }

    setIsRunning(true);
    clearResults();

    try {
      // 测试系统配置CRUD
      await testSystemConfig();
      
      // 测试奖项CRUD
      await testPrizes();
      
      // 测试学生CRUD
      await testStudents();
      
      // 测试抽奖记录CRUD
      await testDrawRecords();
      
      // 测试密码管理
      await testPasswordManagement();
      
      addResult('所有测试', true, '所有CRUD接口测试完成');
    } catch (error) {
      addResult('测试执行', false, `测试过程中发生错误: ${error}`);
    } finally {
      setIsRunning(false);
    }
  };

  const testSystemConfig = async () => {
    try {
      // 测试获取系统配置
      const config = await dbService!.getSystemConfig();
      addResult('获取系统配置', true, '成功获取系统配置', config);

      // 测试更新系统配置
      const newConfig: Partial<SystemConfig> = {
        max_draw_times: 3,
        admin_password: 'test123',
        login_password: 'draw123'
      };
      const updateResult = await dbService!.updateSystemConfig(newConfig);
      addResult('更新系统配置', updateResult, updateResult ? '系统配置更新成功' : '系统配置更新失败');

      // 验证更新后的配置
      const updatedConfig = await dbService!.getSystemConfig();
      addResult('验证配置更新', true, '配置更新验证完成', updatedConfig);
    } catch (error) {
      addResult('系统配置测试', false, `系统配置测试失败: ${error}`);
    }
  };

  const testPrizes = async () => {
    try {
      // 测试获取所有奖项
      const prizes = await dbService!.getAllPrizes();
      addResult('获取所有奖项', true, `成功获取${prizes?.length || 0}个奖项`, prizes);

      // 测试添加奖项
      const newPrize = {
        prize_name: '测试奖品',
        prize_level: 1,
        probability: 0.1,
        total_quantity: 10,
        is_active: true
      };
      const addPrizeResult = await dbService!.addPrize(newPrize);
      addResult('添加奖项', addPrizeResult, addPrizeResult ? '奖项添加成功' : '奖项添加失败', newPrize);

      if (addPrizeResult) {
        // 获取添加的奖项以获取ID
        const allPrizes = await dbService!.getAllPrizes();
        const addedPrize = allPrizes.find(p => p.prize_name === '测试奖品');
        
        if (addedPrize) {
          // 测试更新奖项
          const updatedPrize = { prize_name: '更新后的测试奖品', remaining_quantity: 8 };
          const updateResult = await dbService!.updatePrize(addedPrize.id, updatedPrize);
          addResult('更新奖项', updateResult, updateResult ? '奖项更新成功' : '奖项更新失败', updatedPrize);

          // 测试删除奖项
          const deleteResult = await dbService!.deletePrize(addedPrize.id);
          addResult('删除奖项', deleteResult, deleteResult ? '奖项删除成功' : '奖项删除失败');
        }
      }
    } catch (error) {
      addResult('奖项测试', false, `奖项测试失败: ${error}`);
    }
  };

  const testStudents = async () => {
    try {
      const testStudentId = 'TEST001';
      
      // 测试获取学生
      const student = await dbService!.getStudent(testStudentId);
      addResult('获取学生', true, student ? '学生已存在' : '学生不存在', student);

      // 测试创建/更新学生
      const createResult = await dbService!.createOrUpdateStudent(testStudentId);
      addResult('创建/更新学生', !!createResult, createResult ? '学生操作成功' : '学生操作失败', createResult);

      // 验证学生创建
      const createdStudent = await dbService!.getStudent(testStudentId);
      addResult('验证学生创建', !!createdStudent, createdStudent ? '学生创建验证成功' : '学生创建验证失败', createdStudent);
    } catch (error) {
      addResult('学生测试', false, `学生测试失败: ${error}`);
    }
  };

  const testDrawRecords = async () => {
    try {
      // 测试获取所有抽奖记录
      const records = await dbService!.getAllDrawRecords();
      addResult('获取抽奖记录', true, `成功获取${records?.length || 0}条抽奖记录`, records);

      // 测试创建抽奖记录
      const newRecord = {
        student_id: 'TEST001',
        prize_id: 'test-prize',
        prize_name: '测试奖品',
        prize_level: 1
      };
      const createResult = await dbService!.createDrawRecord(newRecord);
      addResult('创建抽奖记录', !!createResult, createResult ? '抽奖记录创建成功' : '抽奖记录创建失败', createResult);

      // 测试清空抽奖记录
      const clearResult = await dbService!.clearAllDrawRecords();
      addResult('清空抽奖记录', clearResult, clearResult ? '抽奖记录清空成功' : '抽奖记录清空失败');
    } catch (error) {
      addResult('抽奖记录测试', false, `抽奖记录测试失败: ${error}`);
    }
  };

  const testPasswordManagement = async () => {
    try {
      // 测试管理员密码验证
      const adminVerify = await dbService!.verifyAdminPassword('123456');
      addResult('验证管理员密码', true, adminVerify ? '管理员密码验证成功' : '管理员密码验证失败');

      // 测试登录密码验证
      const loginVerify = await dbService!.validateLoginPassword('123456');
      addResult('验证登录密码', true, loginVerify ? '登录密码验证成功' : '登录密码验证失败');

      // 测试修改管理员密码
      const changeAdminResult = await dbService!.changeAdminPassword('newadmin123');
      addResult('修改管理员密码', changeAdminResult, changeAdminResult ? '管理员密码修改成功' : '管理员密码修改失败');

      // 恢复原密码
      if (changeAdminResult) {
        await dbService!.changeAdminPassword('123456');
        addResult('恢复管理员密码', true, '管理员密码已恢复');
      }
    } catch (error) {
      addResult('密码管理测试', false, `密码管理测试失败: ${error}`);
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 p-6">
      <div className="max-w-6xl mx-auto">
        <div className="bg-white rounded-lg shadow-lg p-6">
          <h1 className="text-3xl font-bold text-gray-800 mb-6">CRUD接口兼容性测试</h1>
          
          <div className="mb-6">
            <button
              onClick={runAllTests}
              disabled={isRunning || !dbService}
              className="bg-blue-500 hover:bg-blue-600 disabled:bg-gray-400 text-white px-6 py-2 rounded-lg font-medium transition-colors"
            >
              {isRunning ? '测试进行中...' : '运行所有测试'}
            </button>
            
            <button
              onClick={clearResults}
              disabled={isRunning}
              className="ml-4 bg-gray-500 hover:bg-gray-600 disabled:bg-gray-400 text-white px-6 py-2 rounded-lg font-medium transition-colors"
            >
              清空结果
            </button>
          </div>

          <div className="space-y-4">
            <h2 className="text-xl font-semibold text-gray-700">测试结果</h2>
            
            {testResults.length === 0 ? (
              <p className="text-gray-500">暂无测试结果</p>
            ) : (
              <div className="space-y-2">
                {testResults.map((result, index) => (
                  <div
                    key={index}
                    className={`p-4 rounded-lg border-l-4 ${
                      result.success
                        ? 'bg-green-50 border-green-400 text-green-800'
                        : 'bg-red-50 border-red-400 text-red-800'
                    }`}
                  >
                    <div className="flex items-center justify-between">
                      <div>
                        <span className="font-medium">{result.operation}</span>
                        <span className={`ml-2 px-2 py-1 rounded text-xs ${
                          result.success ? 'bg-green-200 text-green-800' : 'bg-red-200 text-red-800'
                        }`}>
                          {result.success ? '成功' : '失败'}
                        </span>
                      </div>
                    </div>
                    <p className="mt-1 text-sm">{result.message}</p>
                    {result.data && (
                      <details className="mt-2">
                        <summary className="cursor-pointer text-sm font-medium">查看数据</summary>
                        <pre className="mt-1 p-2 bg-gray-100 rounded text-xs overflow-auto">
                          {JSON.stringify(result.data, null, 2)}
                        </pre>
                      </details>
                    )}
                  </div>
                ))}
              </div>
            )}
          </div>

          <div className="mt-8 p-4 bg-blue-50 rounded-lg">
            <h3 className="font-semibold text-blue-800 mb-2">测试说明</h3>
            <ul className="text-sm text-blue-700 space-y-1">
              <li>• 系统配置：测试获取和更新系统配置</li>
              <li>• 奖项管理：测试奖项的增删改查操作</li>
              <li>• 学生管理：测试学生信息的创建和查询</li>
              <li>• 抽奖记录：测试抽奖记录的创建、查询和清空</li>
              <li>• 密码管理：测试管理员和登录密码的验证和修改</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  );
};

export default CrudTest;