import React, { useState, useEffect } from 'react';
import { Button, Typography, Tag, Space, Spin, App, Modal } from 'antd';
import { ClockCircleOutlined, BookOutlined, RightOutlined, ReloadOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useUser } from '../contexts';
import { examSubjectAPI, examTaskAPI, quizAPI } from '../services/api';
import { UserLayout } from '../layouts/UserLayout';
import { formatDate, parseUtcDateTime } from '../utils/validation';

const { Title, Text } = Typography;

interface ExamSubject {
  id: string;
  name: string;
  totalScore: number;
  timeLimitMinutes: number;
  typeRatios: Record<string, number>;
  categoryRatios: Record<string, number>;
  createdAt: string;
}

interface ExamTask {
  id: string;
  name: string;
  subjectId: string;
  startAt: string;
  endAt: string;
  subjectName?: string;
  usedAttempts?: number;
  maxAttempts?: number;
  bestScore?: number;
  totalScore?: number;
}

export const SubjectSelectionPage: React.FC = () => {
  const [subjects, setSubjects] = useState<ExamSubject[]>([]);
  const [tasks, setTasks] = useState<ExamTask[]>([]);
  const [loading, setLoading] = useState(true);
  const navigate = useNavigate();
  const { message } = App.useApp();
  const { user } = useUser();

  useEffect(() => {
    if (!user?.id) {
      message.warning('请先填写个人信息');
      navigate('/');
      return;
    }

    fetchData();
  }, [user?.id, navigate]);

  const fetchData = async () => {
    try {
      setLoading(true);
      if (!user?.id) return;
      const [subjectsRes, tasksRes] = await Promise.all([
        examSubjectAPI.getSubjects(),
        examTaskAPI.getUserTasks(user.id)
      ]) as any;

      setSubjects(subjectsRes.data);
      setTasks(tasksRes.data);
    } catch (error) {
      message.error('获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  const getTaskStatus = (task: ExamTask) => {
    const nowMs = Date.now();
    const startMs = parseUtcDateTime(task.startAt)?.getTime() ?? NaN;
    const endMs = parseUtcDateTime(task.endAt)?.getTime() ?? NaN;
    const usedAttempts = Number(task.usedAttempts) || 0;
    const maxAttempts = Number(task.maxAttempts) || 3;

    // 日期解析失败时，按“已完成/不可开始”处理，避免误分组
    if (!Number.isFinite(startMs) || !Number.isFinite(endMs)) {
      return 'completed';
    }

    if (nowMs < startMs) return 'notStarted';
    if (nowMs > endMs) return 'completed';
    if (usedAttempts >= maxAttempts) return 'completed';
    return 'ongoing';
  };

  const getTasksByStatus = (status: 'ongoing' | 'completed' | 'notStarted') => {
    return tasks.filter(task => getTaskStatus(task) === status);
  };

  const getScoreStatus = (pct: number): '优秀' | '合格' | '不及格' => {
    if (!Number.isFinite(pct)) return '不及格';
    if (pct >= 80) return '优秀';
    if (pct >= 60) return '合格';
    return '不及格';
  };

  const getScoreStatusTagColor = (status: '优秀' | '合格' | '不及格') => {
    if (status === '优秀') return 'green';
    if (status === '合格') return 'blue';
    return 'red';
  };

  const renderBestHistoryTag = (task: ExamTask, subject?: ExamSubject) => {
    const usedAttempts = Number(task.usedAttempts) || 0;
    if (usedAttempts <= 0) return null;

    if (typeof task.bestScore !== 'number') return null;
    const totalScore = Number(subject?.totalScore ?? task.totalScore) || 0;
    const pct = totalScore > 0 ? (task.bestScore / totalScore) * 100 : NaN;
    const status = getScoreStatus(pct);

    return (
      <Tag color={getScoreStatusTagColor(status)} className="text-xs">
        历史最高：{status}
      </Tag>
    );
  };

  const startQuiz = async (taskId: string) => {
    if (!taskId) {
      message.warning('请选择考试任务');
      return;
    }

    const task = tasks.find((t) => t.id === taskId);
    const usedAttempts = Number(task?.usedAttempts) || 0;
    const maxAttempts = Number(task?.maxAttempts) || 3;
    const remainingAttempts = maxAttempts - usedAttempts;

    if (usedAttempts >= maxAttempts) {
      message.error('考试次数已用尽');
      return;
    }

    Modal.confirm({
      title: '确认开始考试',
      content: `是否现在开始考试，你还有${remainingAttempts}次重试机会`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const response = await quizAPI.generateQuiz(user?.id || '', undefined, taskId) as any;
          const { questions, totalScore, timeLimit } = response.data;
          navigate('/quiz', { 
            state: { 
              questions, 
              totalScore, 
              timeLimit,
              taskId: taskId,
              taskName: task?.name || ''
            } 
          });
        } catch (error: any) {
          message.error(error.message || '生成试卷失败');
        }
      }
    });
  };

  const formatTypeRatio = (typeRatios: Record<string, number>) => {
    return Object.entries(typeRatios)
      .filter(([, ratio]) => ratio > 0)
      .map(([type, ratio]) => {
        const typeMap: Record<string, string> = {
          single: '单选题',
          multiple: '多选题',
          truefalse: '判断题',
          fill: '填空题',
          essay: '问答题'
        };
        return `${typeMap[type] || type}: ${ratio}%`;
      })
      .join(', ');
  };

  if (loading) {
    return (
      <UserLayout>
        <div className="flex justify-center items-center h-full min-h-[500px]">
          <Spin size="large" />
        </div>
      </UserLayout>
    );
  }

  return (
    <UserLayout>
      <div className="container mx-auto px-4 max-w-md">

        <div className="grid grid-cols-1 gap-4">


          {/* 考试任务选择 - 按状态分组 */}
          <div>
            <div className="flex items-center mb-3 border-b border-gray-200 pb-1">
              <BookOutlined className="text-lg mr-2 text-mars-400" />
              <div>
                <Title level={4} className="!mb-0 !text-gray-700 !text-base">我的考试任务</Title>
                {user && <Text className="text-sm text-gray-500">欢迎，{user.name}</Text>}
              </div>
              <Button
                type="default"
                size="small"
                icon={<ReloadOutlined />}
                className="ml-auto"
                onClick={fetchData}
              >
                刷新
              </Button>
            </div>

            <div className="space-y-4">
              {/* 进行中 */}
              <div>
                <div className="flex items-center mb-2">
                  <span className="inline-block w-2 h-2 bg-green-500 rounded-full mr-2"></span>
                  <Text className="text-sm font-medium text-gray-700">进行中</Text>
                  <Tag color="green" className="ml-2 text-xs">{getTasksByStatus('ongoing').length}</Tag>
                </div>
                <div className="space-y-2">
                  {getTasksByStatus('ongoing').map((task) => {
                    const subject = subjects.find(s => s.id === task.subjectId);
                    const usedAttempts = Number(task.usedAttempts) || 0;
                    const maxAttempts = Number(task.maxAttempts) || 3;
                    return (
                      <Button
                        key={task.id}
                        type="default"
                        block
                        className="h-auto py-3 px-4 text-left border-l-4 border-l-green-500 hover:border-l-green-600 hover:shadow-md transition-all duration-300"
                        onClick={() => startQuiz(task.id)}
                      >
                        <div className="flex justify-between items-center w-full">
                          <div className="flex-1">
                            <div className="flex items-center mb-1">
                              <Title level={5} className="mb-0 text-gray-800 !text-sm">
                                {task.name}
                              </Title>
                              {subject && (
                                <div className="flex items-center ml-auto">
                                  <span className="mr-1 text-gray-400 text-xs">（时长:</span>
                                  <Text className="text-gray-600 text-xs">{subject.timeLimitMinutes}分钟）</Text>
                                </div>
                              )}
                            </div>
                            <div className="flex justify-between items-center mb-2">
                              <div className="flex items-center">
                                <BookOutlined className="mr-1 text-gray-400 text-xs" />
                                <Text className="text-gray-600 text-xs">{subject?.name || '未知科目'}</Text>
                              </div>
                              <div>
                                <Tag color="green" className="text-xs">
                                  {usedAttempts}/{maxAttempts}
                                </Tag>
                                {renderBestHistoryTag(task, subject)}
                              </div>
                            </div>
                            <div className="flex justify-between items-center mb-2">
                              <div className="flex items-center">
                                <ClockCircleOutlined className="mr-1 text-gray-400 text-xs" />
                                <Text className="text-gray-600 text-xs">
                                  {formatDate(task.startAt)} - {formatDate(task.endAt)}
                                </Text>
                              </div>
                              <div className="text-green-600">
                                <Text className="text-xs px-2 py-1 rounded border border-green-200 bg-green-50">点击开始考试</Text>
                              </div>
                            </div>
                          </div>
                        </div>
                      </Button>
                    );
                  })}
                  {getTasksByStatus('ongoing').length === 0 && (
                    <div className="text-center py-4 bg-gray-50 border-dashed border-2 border-gray-200 rounded">
                      <Text type="secondary" className="text-sm">暂无进行中的任务</Text>
                    </div>
                  )}
                </div>
              </div>

              {/* 已完成 */}
              <div>
                <div className="flex items-center mb-2">
                  <span className="inline-block w-2 h-2 bg-gray-400 rounded-full mr-2"></span>
                  <Text className="text-sm font-medium text-gray-700">已完成</Text>
                  <Tag color="default" className="ml-2 text-xs">{getTasksByStatus('completed').length}</Tag>
                </div>
                <div className="space-y-2">
                  {getTasksByStatus('completed').map((task) => {
                    const subject = subjects.find(s => s.id === task.subjectId);
                    const usedAttempts = Number(task.usedAttempts) || 0;
                    const maxAttempts = Number(task.maxAttempts) || 3;
                    const attemptsExhausted = usedAttempts >= maxAttempts;
                    const endMs = parseUtcDateTime(task.endAt)?.getTime() ?? NaN;
                    const isExpired = Number.isFinite(endMs) ? endMs < Date.now() : true;
                    const isDisabled = attemptsExhausted || isExpired;
                    return (
                      <Button
                        key={task.id}
                        type="default"
                        block
                        disabled={isDisabled}
                        className={`h-auto py-3 px-4 text-left border-l-4 border-l-gray-400 hover:border-l-gray-500 hover:shadow-md transition-all duration-300 ${isDisabled ? 'opacity-50 cursor-not-allowed' : ''}`}
                        onClick={() => !isDisabled && startQuiz(task.id)}
                      >
                        <div className="flex justify-between items-center w-full">
                          <div className="flex-1">
                            <div className="flex justify-between items-center mb-1">
                              <Title level={5} className="mb-0 text-gray-800 !text-sm">
                                {task.name}
                              </Title>
                              {subject && (
                                <div className="flex items-center ml-auto">
                                  <span className="mr-1 text-gray-400 text-xs">（时长:</span>
                                  <Text className="text-gray-600 text-xs">{subject.timeLimitMinutes}分钟）</Text>
                                </div>
                              )}
                            </div>
                            <div className="flex justify-between items-center mb-2">
                              <div className="flex items-center">
                                <BookOutlined className="mr-1 text-gray-400 text-xs" />
                                <Text className="text-gray-600 text-xs">{subject?.name || '未知科目'}</Text>
                              </div>
                              <div>
                                <Tag color={attemptsExhausted ? 'red' : 'default'} className="text-xs">
                                  {usedAttempts}/{maxAttempts}
                                </Tag>
                                {renderBestHistoryTag(task, subject)}
                              </div>
                            </div>
                            <div className="flex justify-between items-center mb-2">
                              <div className="flex items-center">
                                <ClockCircleOutlined className="mr-1 text-gray-400 text-xs" />
                                <Text className="text-gray-600 text-xs">
                                  {formatDate(task.startAt)} - {formatDate(task.endAt)}
                                </Text>
                              </div>
                              {attemptsExhausted ? (
                                <div className="text-red-600">
                                  <Text className="text-xs px-2 py-1 rounded border border-red-200 bg-red-50">次数用尽</Text>
                                </div>
                              ) : (
                                <div className="text-gray-400">
                                  <Text className="text-xs px-2 py-1 rounded border border-gray-200 bg-gray-50">已结束</Text>
                                </div>
                              )}
                            </div>
                          </div>
                        </div>
                      </Button>
                    );
                  })}
                  {getTasksByStatus('completed').length === 0 && (
                    <div className="text-center py-4 bg-gray-50 border-dashed border-2 border-gray-200 rounded">
                      <Text type="secondary" className="text-sm">暂无已完成的任务</Text>
                    </div>
                  )}
                </div>
              </div>

              {/* 未开始 */}
              <div>
                <div className="flex items-center mb-2">
                  <span className="inline-block w-2 h-2 bg-blue-400 rounded-full mr-2"></span>
                  <Text className="text-sm font-medium text-gray-700">未开始</Text>
                  <Tag color="blue" className="ml-2 text-xs">{getTasksByStatus('notStarted').length}</Tag>
                </div>
                <div className="space-y-2">
                  {getTasksByStatus('notStarted').map((task) => {
                    const subject = subjects.find(s => s.id === task.subjectId);
                    const usedAttempts = Number(task.usedAttempts) || 0;
                    const maxAttempts = Number(task.maxAttempts) || 3;
                    return (
                      <Button
                        key={task.id}
                        type="default"
                        block
                        disabled
                        className="h-auto py-3 px-4 text-left border-l-4 border-l-blue-400 opacity-75 cursor-not-allowed"
                      >
                        <div className="flex justify-between items-center w-full">
                          <div className="flex-1">
                            <div className="flex justify-between items-center mb-1">
                              <Title level={5} className="mb-0 text-gray-800 !text-sm">
                                {task.name}
                              </Title>
                              {subject && (
                                <div className="flex items-center ml-auto">
                                  <span className="mr-1 text-gray-400 text-xs">（时长:</span>
                                  <Text className="text-gray-600 text-xs">{subject.timeLimitMinutes}分钟）</Text>
                                </div>
                              )}
                            </div>
                            <div className="flex justify-between items-center mb-2">
                              <div className="flex items-center">
                                <BookOutlined className="mr-1 text-gray-400 text-xs" />
                                <Text className="text-gray-600 text-xs">{subject?.name || '未知科目'}</Text>
                              </div>
                              <div>
                                <Tag color="blue" className="text-xs">
                                  {usedAttempts}/{maxAttempts}
                                </Tag>
                                {renderBestHistoryTag(task, subject)}
                              </div>
                            </div>
                            <div className="flex justify-between items-center mb-2">
                              <div className="flex items-center">
                                <ClockCircleOutlined className="mr-1 text-gray-400 text-xs" />
                                <Text className="text-gray-600 text-xs">
                                  {formatDate(task.startAt)} - {formatDate(task.endAt)}
                                </Text>
                              </div>
                              <div className="text-blue-600">
                                <Text className="text-xs px-2 py-1 rounded border border-blue-200 bg-blue-50">未开始</Text>
                              </div>
                            </div>
                          </div>
                        </div>
                      </Button>
                    );
                  })}
                  {getTasksByStatus('notStarted').length === 0 && (
                    <div className="text-center py-4 bg-gray-50 border-dashed border-2 border-gray-200 rounded">
                      <Text type="secondary" className="text-sm">暂无未开始的任务</Text>
                    </div>
                  )}
                </div>
              </div>
            </div>


          </div>
        </div>

        <div className="mt-6 text-center">
          <Button
            type="default"
            size="large"
            className="px-4 h-10 text-sm hover:border-mars-500 hover:text-mars-500"
            onClick={() => navigate('/tasks')}
          >
            查看我的答题记录
          </Button>
        </div>
      </div>
    </UserLayout>
  );
};
