import { useState, useEffect } from 'react';
import { Card, Button, Descriptions, App } from 'antd';
import { useParams, useNavigate } from 'react-router-dom';
import { useUser } from '../contexts';
import { quizAPI } from '../services/api';
import { formatDateTime } from '../utils/validation';
import { UserLayout } from '../layouts/UserLayout';

const { Item } = Descriptions;

interface QuizRecord {
  id: string;
  userId: string;
  totalScore: number;
  correctCount: number;
  totalCount: number;
  scorePercentage: number;
  status: '不及格' | '合格' | '优秀';
  createdAt: string;
}

interface QuizAnswer {
  id: string;
  questionId: string;
  questionContent?: string;
  questionType?: string;
  userAnswer: string | string[];
  score: number;
  isCorrect: boolean;
  correctAnswer?: string | string[];
  questionScore?: number;
  questionAnalysis?: string;
}

const StatusIcon = ({ status }: { status: QuizRecord['status'] }) => {
  const colorClass =
    status === '优秀' ? 'text-green-500' : status === '合格' ? 'text-blue-500' : 'text-red-500';

  const renderInner = () => {
    if (status === '优秀') {
      // 五角星（实心）
      return (
        <path
          d="M12 3.6l2.63 5.33 5.89.86-4.26 4.15 1.01 5.86L12 17.69 6.73 19.8l1.01-5.86-4.26-4.15 5.89-.86L12 3.6z"
          fill="currentColor"
          stroke="none"
          className="text-yellow-500"
        />
      );
    }

    if (status === '合格') {
      // 对号（空心）
      return <path d="M7.5 12.2l3 3L16.8 9" />;
    }

    // 感叹号（空心）
    return (
      <>
        <path d="M12 7v6" />
        <path d="M12 16.8h.01" />
      </>
    );
  };

  return (
    <svg
      viewBox="0 0 24 24"
      width="32"
      height="32"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
      className={colorClass}
    >
      <circle cx="12" cy="12" r="10" />
      {renderInner()}
    </svg>
  );
};

const ResultPage = () => {
  const { id: recordId } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { message } = App.useApp();
  const { user } = useUser();
  const [record, setRecord] = useState<QuizRecord | null>(null);
  const [answers, setAnswers] = useState<QuizAnswer[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!recordId) {
      message.error('无效的记录ID');
      navigate('/');
      return;
    }

    fetchResultDetail();
  }, [recordId, navigate]);

  const fetchResultDetail = async () => {
    try {
      setLoading(true);
      const response = await quizAPI.getRecordDetail(recordId!) as any;
      const payload = response?.data ?? response;
      setRecord(payload?.record ?? null);
      setAnswers(Array.isArray(payload?.answers) ? payload.answers : []);
    } catch (error: any) {
      message.error(error.message || '获取答题结果失败');
      setRecord(null);
      setAnswers([]);
    } finally {
      setLoading(false);
    }
  };

  const handleBackToHome = () => {
    navigate('/tasks');
  };

  const getTagColor = (type: string) => {
    switch (type) {
      case 'single':
        return 'bg-blue-100 text-blue-800';
      case 'multiple':
        return 'bg-purple-100 text-purple-800';
      case 'judgment':
        return 'bg-orange-100 text-orange-800';
      case 'text':
        return 'bg-green-100 text-green-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  const parseAnswerList = (ans: string | string[] | undefined): string[] => {
    if (!ans) return [];
    if (Array.isArray(ans)) return ans;
    try {
      const parsed = JSON.parse(ans);
      if (Array.isArray(parsed)) return parsed;
      return [ans];
    } catch {
      return [ans];
    }
  };

  const renderUserAnswer = (answer: QuizAnswer) => {
    const userList = parseAnswerList(answer.userAnswer);
    const correctList = parseAnswerList(answer.correctAnswer);
    const correctSet = new Set(correctList);

    if (answer.questionType === 'multiple') {
      return (
        <span className="font-medium">
          {userList.map((item, idx) => {
            const isWrong = !correctSet.has(item);
            return (
              <span key={idx} className={isWrong ? 'text-red-600' : 'text-gray-800'}>
                {idx > 0 && ', '}
                {item}
              </span>
            );
          })}
        </span>
      );
    }
    
    // 非多选题，直接展示
    return (
      <span className={answer.isCorrect ? 'text-green-600 font-medium' : 'text-red-600 font-medium'}>
         {Array.isArray(answer.userAnswer) ? answer.userAnswer.join(', ') : answer.userAnswer}
      </span>
    );
  };

  const renderCorrectAnswer = (answer: QuizAnswer) => {
    const userList = parseAnswerList(answer.userAnswer);
    const correctList = parseAnswerList(answer.correctAnswer);
    const userSet = new Set(userList);

    if (answer.questionType === 'multiple') {
      return (
        <span className="font-medium">
          {correctList.map((item, idx) => {
            const isMissed = !userSet.has(item); // 用户没选这个正确选项
            return (
              <span key={idx} className={isMissed ? 'text-red-600' : 'text-green-600'}>
                {idx > 0 && ', '}
                {item}
              </span>
            );
          })}
        </span>
      );
    }

    return (
      <span className="text-green-600 font-medium">
        {Array.isArray(answer.correctAnswer)
          ? answer.correctAnswer.join(', ')
          : answer.correctAnswer || '未知'}
      </span>
    );
  };

  if (loading) {
    return (
      <UserLayout>
        <div className="flex justify-center items-center h-full min-h-[400px]">
          <div className="text-center">
            <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-mars-600 mx-auto mb-3"></div>
            <p className="text-gray-600 text-sm">正在加载答题结果...</p>
          </div>
        </div>
      </UserLayout>
    );
  }

  if (!record) {
    return (
      <UserLayout>
        <div className="flex justify-center items-center h-full min-h-[400px]">
          <div className="text-center">
            <p className="text-gray-600 mb-4 text-sm">答题记录不存在</p>
            <Button type="primary" onClick={handleBackToHome} className="bg-mars-500 hover:bg-mars-600 text-sm">
              返回首页
            </Button>
          </div>
        </div>
      </UserLayout>
    );
  }

  const correctRate = ((record.correctCount / record.totalCount) * 100).toFixed(1);
  const getStatusColor = (status: string) => {
  switch (status) {
    case '不及格':
      return 'bg-red-100 text-red-800 border-red-200';
    case '合格':
      return 'bg-teal-50 text-[#008C8C] border-teal-100';
    case '优秀':
      return 'bg-green-100 text-green-800 border-green-200';
    default:
      return 'bg-gray-100 text-gray-800 border-gray-200';
  }
};

  return (
    <UserLayout>
      <div className="max-w-md mx-auto px-4 py-6">
        {/* 结果概览 */}
        <Card className="shadow-sm mb-6 rounded-2xl border-t-4 border-t-[#008C8C]" bodyStyle={{ padding: '20px' }}>
          <div className="flex items-start gap-4">
            <div className="flex-shrink-0 mt-0.5">
              <StatusIcon status={record.status} />
            </div>
            <div className="flex-1 min-w-0">
              <div className="text-base font-bold text-gray-900 mb-1">
                答题完成！您的得分是 {record.totalScore} 分
              </div>
              <div className="flex items-center gap-2 mb-4">
                <span className={`px-2 py-0.5 rounded text-xs font-medium border ${getStatusColor(record.status)}`}>
                  {record.status}
                </span>
                <span className="text-xs text-gray-500">
                  正确率 {correctRate}% ({record.correctCount}/{record.totalCount})
                </span>
              </div>
              <Button type="primary" onClick={handleBackToHome} className="bg-[#008C8C] hover:bg-[#00796B] border-none px-6 h-8 text-xs rounded-lg shadow-sm">
                返回答题记录
              </Button>
            </div>
          </div>
        </Card>

        {/* 基本信息 */}
        <Card className="shadow-sm mb-6 rounded-2xl" bodyStyle={{ padding: '20px' }}>
          <h3 className="text-base font-bold mb-4 text-gray-900 border-l-4 border-[#008C8C] pl-3">答题信息</h3>
          <Descriptions bordered column={1} size="small" className="text-xs">
            <Item label="答题时间">{formatDateTime(record.createdAt)}</Item>
            <Item label="总题数">{record.totalCount} 题</Item>
            <Item label="正确数">{record.correctCount} 题</Item>
            <Item label="总得分">{record.totalScore} 分</Item>
            <Item label="得分占比">{record.scorePercentage.toFixed(1)}%</Item>
            <Item label="考试状态">{record.status}</Item>
          </Descriptions>
        </Card>

        {/* 答案详情 */}
        <Card className="shadow-sm rounded-2xl">
          <h3 className="text-base font-bold mb-4 text-gray-900 border-l-4 border-[#008C8C] pl-3">答案详情</h3>
          <div className="space-y-4">
            {answers.map((answer, index) => (
              <div
                key={answer.id}
                className={`p-3 rounded-lg border ${
                  answer.isCorrect
                    ? 'border-green-200 bg-green-50/50'
                    : 'border-red-200 bg-red-50/50'
                }`}
              >
                <div className="flex justify-between items-start mb-1.5">
                  <div className="flex items-center gap-1.5">
                    <span className="font-medium text-gray-800 text-sm">
                      第 {index + 1} 题
                    </span>
                    <span className={`${getTagColor(answer.questionType || '')} px-1.5 py-0.5 rounded text-xs`}>
                      {answer.questionType === 'single' ? '单选题' : 
                       answer.questionType === 'multiple' ? '多选题' : 
                       answer.questionType === 'judgment' ? '判断题' : '简答题'}
                    </span>
                  </div>
                  <span
                    className={`px-1.5 py-0.5 rounded text-xs ${
                      answer.isCorrect
                        ? 'bg-green-100 text-green-800'
                        : 'bg-red-100 text-red-800'
                    }`}
                  >
                    {answer.isCorrect ? '正确' : '错误'}
                  </span>
                </div>
                <div className="mb-1.5">
                  <span className="text-gray-600 text-xs">题目：</span>
                  <span className="text-gray-800 font-medium text-sm">{answer.questionContent || '题目内容加载失败'}</span>
                </div>
                <div className="mb-1.5">
                  <span className="text-gray-600 text-xs">您的答案：</span>
                  {renderUserAnswer(answer)}
                </div>
                {!answer.isCorrect && (
                  <div className="mb-1.5">
                    <span className="text-gray-600 text-xs">正确答案：</span>
                    {renderCorrectAnswer(answer)}
                  </div>
                )}
                {String(answer.questionAnalysis ?? '').trim() ? (
                  <div className="mb-1.5">
                    <span className="text-gray-600 text-xs">解析：</span>
                    <span className="text-gray-800 whitespace-pre-wrap text-sm">{answer.questionAnalysis}</span>
                  </div>
                ) : null}
                <div className="mb-1 pt-1.5 border-t border-gray-100 mt-1.5">
                  <span className="text-gray-500 text-xs">
                    本题分值：{answer.questionScore || 0} 分，你的得分：<span className="font-medium text-gray-800">{answer.score}</span> 分
                  </span>
                </div>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </UserLayout>
  );
};

export default ResultPage;
