import React, { useState, useCallback } from 'react';
import { useNavigate } from "react-router";
import type { ClassroomData } from '../../../share/types_stock.ts';
import dayjs from 'dayjs';
import { message } from 'antd';
import { ClassroomDataAPI } from '../../api/classroom_data.ts';
import { ClassroomStatus } from '../../../share/types_stock.ts';

// 教室号输入页面
function ExamIndex() {
  const [classroom, setClassroom] = useState('');
  const navigate = useNavigate();

  const [classroomData, setClassroomData] = useState<ClassroomData | null>(null);
  const [isLoading, setIsLoading] = useState(false);

  const handleJoinTraining = useCallback(async () => {
    if (!classroom) {
      message.error('教室号不能为空');
      return;
    }

    try {
      setIsLoading(true);
      const response = await ClassroomDataAPI.getClassroomDatas({ classroom_no: classroom });
      
      if (!response.data?.length) {
        message.error('教室不存在');
        setClassroomData(null);
        return;
      }

      const data = response.data[0];
      setClassroomData(data);

      if (data.status !== ClassroomStatus.OPEN) {
        message.error('该教室已关闭');
        return;
      }

      // 将教室号作为参数传递到答题页
      navigate(`/mobile/exam/card?classroom=${classroom}`);
    } catch (error) {
      message.error('获取教室数据失败');
      setClassroomData(null);
    } finally {
      setIsLoading(false);
    }
  }, [navigate, classroom]);

  if (isLoading) {
    return <div className="flex items-center justify-center min-h-screen">加载中...</div>;
  }

  return (
    <div className="flex flex-col items-center justify-center min-h-screen bg-gray-100">
      <div className="w-full max-w-md space-y-8">
        <div className="text-center">
          <h2 className="text-3xl font-bold text-gray-900">股票训练答题卡系统</h2>
          <p className="mt-2 text-gray-600">
            {classroom ? `教室号: ${classroom}` : '请输入教室号开始答题'}
          </p>
          {classroomData && (
            <div className="mt-2 text-sm text-gray-500">
              <p>训练日期: {dayjs(classroomData.training_date).format('YYYY-MM-DD')}</p>
              <p>代码: {classroomData.code}</p>
            </div>
          )}
        </div>
        
        <div className="mt-8 space-y-4">
          <input
            type="text"
            value={classroom}
            onChange={(e) => setClassroom(e.target.value)}
            placeholder="请输入教室号"
            className="w-full px-4 py-3 text-lg border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>

        <button
          onClick={handleJoinTraining}
          className="w-full px-8 py-3 text-lg font-medium text-white bg-blue-500 rounded-lg hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors"
        >
          开始答题
        </button>
      </div>
    </div>
  );
}

export default ExamIndex;