import React, { useState, useCallback, useEffect } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useNavigate, useSearchParams } from "react-router";
import dayjs from 'dayjs';
import { message } from 'antd';
import { Skeleton } from 'antd';

// 昵称输入页面
function ExamIndex() {
  const [nickname, setNickname] = useState('');
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const classroom = searchParams.get('classroom');

  const { data: classroomData, isLoading } = useQuery({
    queryKey: ['classroom', classroom],
    queryFn: async () => {
      if (!classroom) return null;
      const response = await fetch(`/api/v1/classroom?classroom_no=${classroom}`);
      const data = await response.json();
      if (!data.success) {
        message.error(data.message || '获取教室数据失败');
        return null;
      }
      return data.data?.[0] || null;
    },
    enabled: !!classroom
  });

  useEffect(() => {
    if (classroomData && classroomData.status !== "1") {
      message.error('该教室已关闭');
    }
  }, [classroomData]);

  const handleJoinTraining = useCallback(() => {
    if (!nickname.trim()) {
      message.error('请输入昵称');
      return;
    }
    if (!classroom) {
      message.error('教室号不能为空');
      return;
    }
    if (!classroomData) {
      message.error('教室不存在');
      return;
    }
    if (classroomData.status !== "1") {
      message.error('该教室已关闭');
      return;
    }
    // 将昵称和教室号作为参数传递到答题页
    navigate(`/exam/card?nickname=${encodeURIComponent(nickname)}&classroom=${classroom}`);
  }, [nickname, navigate, classroom, classroomData]);

  if (isLoading) {
    return (
      <div className="flex flex-col items-center justify-center min-h-screen p-4">
        <Skeleton active paragraph={{ rows: 4 }} />
      </div>
    );
  }

  return (
    <div className="flex flex-col items-center justify-center min-h-screen bg-gray-100 p-4">
      <div className="w-full max-w-md space-y-8">
        <div className="text-center">
          <h2 className="text-2xl 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">
          <input
            type="text"
            value={nickname}
            onChange={(e) => setNickname(e.target.value)}
            placeholder="请输入昵称"
            className="w-full px-4 py-3 text-base border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            onKeyPress={(e) => e.key === 'Enter' && handleJoinTraining()}
          />
        </div>

        <button
          onClick={handleJoinTraining}
          disabled={!classroomData || classroomData.status !== "1"}
          className={`w-full px-8 py-3 text-base font-medium text-white rounded-lg focus:outline-none focus:ring-2 focus:ring-offset-2 transition-colors ${
            !classroomData || classroomData.status !== "1"
              ? 'bg-gray-400 cursor-not-allowed'
              : 'bg-blue-500 hover:bg-blue-600 focus:ring-blue-500'
          }`}
        >
          开始答题
        </button>
      </div>
    </div>
  );
}

export default ExamIndex;