import React, { useState, useCallback } from 'react';
import { useNavigate } from "react-router";
import dayjs from 'dayjs';
import { classroomDataClient } from '@/client/api';
import { ClassroomStatus } from '@/server/modules/classroom/classroom-data.schema';
import type { InferResponseType } from 'hono/client';
import { toast } from 'sonner';

type ClassroomDataResponse = InferResponseType<typeof classroomDataClient.$get, 200>;
type ClassroomData = ClassroomDataResponse['data'][0];
// 教室号输入页面
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) {
      toast.error('教室号不能为空');
      return;
    }

    try {
      setIsLoading(true);
      const response = await classroomDataClient.$get({
        query: { filters: JSON.stringify({ classroomNo: classroom }) }
      });
      
      if (response.status !== 200) {
        toast.error('获取教室数据失败');
        setClassroomData(null);
        return;
      }
      
      const result = await response.json();
      if (!result.data?.length) {
        toast.error('教室不存在');
        setClassroomData(null);
        return;
      }

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

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

      // 将教室号作为参数传递到答题页
      navigate(`/mobile/exam/card?classroom=${classroom}`);
    } catch (error) {
      toast.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.trainingDate).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;