"use client";

/**
 * 考试结果页面（ai14）
 *
 * 路由：/my-exams/[id]/result
 * 展示考试得分、评级、逐题回顾、答题摘要
 */

import { useState, useEffect } from "react";
import { useParams, useRouter } from "next/navigation";
import { cn } from "@/lib/exam-types";
import type {
  AnswerInput,
  ExamResult,
  ExamResultSummary,
  QuestionResult,
} from "@/lib/exam-types";
import {
  TeacherAnnotationOverlay,
  type TeacherAnnotation,
} from "@/components/teacher-annotation-overlay";

const GRAPHQL_ENDPOINT =
  process.env.NEXT_PUBLIC_GRAPHQL_ENDPOINT ?? "/api/v1/student/graphql";
const IS_MOCKING = process.env.NEXT_PUBLIC_API_MOCKING === "enabled";

/** 创建模拟考试结果数据 */
function createMockExamResult(examId: string): ExamResult {
  return {
    examId,
    examName: "期末考试 · 数学综合测试",
    score: 78,
    maxScore: 100,
    grade: "B+",
    submittedAt: new Date().toISOString(),
    durationSeconds: 3245,
    questionResults: [
      {
        questionId: "q1",
        questionContent: "已知函数 f(x) = x² + 2x + 1，求 f(2) 的值。",
        questionType: "single-choice",
        studentAnswer: { type: "single-choice", optionId: "c" },
        correctAnswer: { type: "single-choice", optionId: "c" },
        isCorrect: true,
        isAnswered: true,
        explanation: "f(2) = 2² + 2×2 + 1 = 4 + 4 + 1 = 9",
        maxScore: 10,
        earnedScore: 10,
      },
      {
        questionId: "q2",
        questionContent: "下列哪些是质数？（多选）",
        questionType: "multiple-choice",
        studentAnswer: { type: "multiple-choice", optionIds: ["a", "c", "d"] },
        correctAnswer: { type: "multiple-choice", optionIds: ["a", "c"] },
        isCorrect: false,
        isAnswered: true,
        explanation:
          "9 = 3 × 3，不是质数。质数是只能被 1 和自身整除的大于 1 的自然数。",
        maxScore: 15,
        earnedScore: 8,
      },
      {
        questionId: "q3",
        questionContent: "sin(30°) = ______",
        questionType: "fill-blank",
        studentAnswer: { type: "fill-blank", values: ["0.5"] },
        correctAnswer: { type: "fill-blank", values: ["1/2"] },
        isCorrect: true,
        isAnswered: true,
        explanation: "sin(30°) = 1/2 = 0.5",
        maxScore: 10,
        earnedScore: 10,
      },
      {
        questionId: "q4",
        questionContent: "简述导数的定义。",
        questionType: "short-answer",
        studentAnswer: {
          type: "short-answer",
          text: "导数是函数在某点的瞬时变化率。",
        },
        correctAnswer: null,
        isCorrect: true,
        isAnswered: true,
        explanation:
          "导数是函数在某一点的瞬时变化率，即当自变量增量趋于零时函数增量与自变量增量之比的极限。",
        maxScore: 20,
        earnedScore: 18,
      },
      {
        questionId: "q5",
        questionContent: "论述微积分的基本思想及其在现代科学中的应用。",
        questionType: "essay",
        studentAnswer: null,
        correctAnswer: null,
        isCorrect: false,
        isAnswered: false,
        explanation:
          "本题未作答。微积分的基本思想包括极限、微分和积分，广泛应用于物理学、工程学、经济学等领域。",
        maxScore: 45,
        earnedScore: 0,
      },
    ],
  };
}

/** 模拟教师批注数据（P5 阶段，后续接入 teacher-bff 批注 API） */
const MOCK_ANNOTATIONS: TeacherAnnotation[] = [
  {
    id: "ann-001",
    questionId: "q2",
    type: "comment",
    teacherName: "李老师",
    content: "注意 9 不是质数，9 = 3 × 3。多选题需要逐项验证。",
    createdAt: new Date().toISOString(),
  },
  {
    id: "ann-002",
    questionId: "q4",
    type: "correction",
    teacherName: "李老师",
    content: "定义表述不够完整，应强调极限概念。导数的严格定义需要用到极限运算。",
    createdAt: new Date().toISOString(),
  },
  {
    id: "ann-003",
    questionId: "q4",
    type: "comment",
    teacherName: "李老师",
    content: "思路正确，但建议补充数学符号表示：f'(x₀) = lim[Δx→0] (f(x₀+Δx) - f(x₀)) / Δx",
    createdAt: new Date().toISOString(),
  },
  {
    id: "ann-004",
    questionId: "q5",
    type: "comment",
    teacherName: "李老师",
    content: "本题未作答，建议复习微积分基本定理及其在物理学中的位移-速度关系应用。",
    createdAt: new Date().toISOString(),
  },
];

/** 获取考试结果（API 或 Mock） */
async function fetchExamResult(examId: string): Promise<ExamResult> {
  if (IS_MOCKING) {
    await new Promise((r) => setTimeout(r, 300));
    return createMockExamResult(examId);
  }
  const response = await fetch(GRAPHQL_ENDPOINT, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      query: `query ExamResult($examId: ID!) {
        examResult(examId: $examId) {
          examId examName score maxScore grade submittedAt durationSeconds
          questionResults {
            questionId questionContent questionType
            studentAnswer correctAnswer
            isCorrect isAnswered explanation maxScore earnedScore
          }
        }
      }`,
      variables: { examId },
    }),
  });
  if (!response.ok) throw new Error(`结果加载失败: ${response.status}`);
  const result = (await response.json()) as {
    data?: { examResult?: ExamResult };
    errors?: Array<{ message: string }>;
  };
  if (result.errors?.length)
    throw new Error(result.errors[0]?.message ?? "查询失败");
  if (!result.data?.examResult) throw new Error("结果数据为空");
  return result.data.examResult;
}

/** 计算结果摘要 */
function computeSummary(results: QuestionResult[]): ExamResultSummary {
  const totalQuestions = results.length;
  const correctCount = results.filter((r) => r.isCorrect).length;
  const unansweredCount = results.filter((r) => !r.isAnswered).length;
  const wrongCount = totalQuestions - correctCount - unansweredCount;
  return { totalQuestions, correctCount, wrongCount, unansweredCount };
}

/** 格式化答案为可读文本 */
function formatAnswer(answer: AnswerInput | null): string {
  if (!answer) return "未作答";
  switch (answer.type) {
    case "single-choice":
      return `选项 ${answer.optionId.toUpperCase()}`;
    case "multiple-choice":
      return answer.optionIds.map((id) => id.toUpperCase()).join("、");
    case "fill-blank":
      return answer.values.join("、");
    case "short-answer":
    case "essay":
      return answer.text || "（空）";
    default:
      return "未知格式";
  }
}

/** 格式化时长 */
function formatDuration(seconds: number): string {
  const h = Math.floor(seconds / 3600);
  const m = Math.floor((seconds % 3600) / 60);
  const s = seconds % 60;
  return [h, m, s].map((n) => String(n).padStart(2, "0")).join(":");
}

export default function ExamResultPage(): JSX.Element {
  const params = useParams();
  const router = useRouter();
  const examId =
    typeof params?.id === "string"
      ? params.id
      : Array.isArray(params?.id)
        ? params.id[0]
        : "";

  const [result, setResult] = useState<ExamResult | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!examId) {
      setError("考试 ID 缺失");
      setLoading(false);
      return;
    }
    fetchExamResult(examId)
      .then((data) => {
        setResult(data);
        setLoading(false);
      })
      .catch((err: unknown) => {
        setError(err instanceof Error ? err.message : "加载失败");
        setLoading(false);
      });
  }, [examId]);

  if (loading) {
    return (
      <div className="flex h-screen items-center justify-center bg-paper">
        <div className="text-center">
          <p className="font-serif text-xl text-ink">加载结果中…</p>
        </div>
      </div>
    );
  }

  if (error || !result) {
    return (
      <div className="flex h-screen items-center justify-center bg-paper">
        <div className="text-center">
          <p className="font-serif text-xl text-danger">结果加载失败</p>
          <p className="mt-sm text-sm text-ink-muted">{error ?? "未知错误"}</p>
          <button
            type="button"
            onClick={() => router.push("/my-exams")}
            className="mt-lg rounded bg-accent px-lg py-sm text-sm text-paper hover:bg-accent-hover"
          >
            返回考试列表
          </button>
        </div>
      </div>
    );
  }

  const summary = computeSummary(result.questionResults);
  const scorePercentage = Math.round((result.score / result.maxScore) * 100);

  return (
    <div className="min-h-screen bg-paper">
      <div className="mx-auto max-w-4xl px-xl py-xl">
        {/* === 结果概要 === */}
        <div className="rounded-lg border border-rule bg-paper p-xl shadow-card">
          <div className="flex items-center justify-between">
            <div>
              <h1 className="font-serif text-2xl text-ink">
                {result.examName}
              </h1>
              <p className="mt-xs text-sm text-ink-muted">
                提交时间：{new Date(result.submittedAt).toLocaleString("zh-CN")}
              </p>
              <p className="mt-xs text-sm text-ink-muted">
                用时：{formatDuration(result.durationSeconds)}
              </p>
            </div>
            <div className="text-right">
              <div className="font-mono text-4xl text-accent">
                {result.score}
                <span className="text-lg text-ink-muted">
                  /{result.maxScore}
                </span>
              </div>
              <div
                className={cn(
                  "mt-xs inline-block rounded px-sm py-xs text-sm font-medium",
                  scorePercentage >= 80 && "bg-success/10 text-success",
                  scorePercentage >= 60 &&
                    scorePercentage < 80 &&
                    "bg-warning/10 text-warning",
                  scorePercentage < 60 && "bg-danger/10 text-danger",
                )}
              >
                {result.grade} · {scorePercentage}%
              </div>
            </div>
          </div>
        </div>

        {/* === 答题摘要 === */}
        <div className="mt-lg grid grid-cols-4 gap-md">
          <div className="rounded-lg border border-rule bg-paper p-md text-center shadow-paper">
            <div className="font-mono text-2xl text-ink">
              {summary.totalQuestions}
            </div>
            <div className="text-xs text-ink-muted">总题数</div>
          </div>
          <div className="rounded-lg border border-rule bg-paper p-md text-center shadow-paper">
            <div className="font-mono text-2xl text-success">
              {summary.correctCount}
            </div>
            <div className="text-xs text-ink-muted">答对</div>
          </div>
          <div className="rounded-lg border border-rule bg-paper p-md text-center shadow-paper">
            <div className="font-mono text-2xl text-danger">
              {summary.wrongCount}
            </div>
            <div className="text-xs text-ink-muted">答错</div>
          </div>
          <div className="rounded-lg border border-rule bg-paper p-md text-center shadow-paper">
            <div className="font-mono text-2xl text-ink-muted">
              {summary.unansweredCount}
            </div>
            <div className="text-xs text-ink-muted">未答</div>
          </div>
        </div>

        {/* === 逐题回顾 === */}
        <div className="mt-xl">
          <h2 className="font-serif text-xl text-ink">逐题回顾</h2>
          <div className="mt-md space-y-md">
            {result.questionResults.map((qr, idx) => (
              <div
                key={qr.questionId}
                className="rounded-lg border border-rule bg-paper p-lg shadow-paper"
              >
                {/* 题头 */}
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-sm">
                    <span className="font-mono text-sm text-ink-muted">
                      第 {idx + 1} 题
                    </span>
                    <span className="text-xs text-ink-subtle">
                      {qr.questionType === "single-choice" && "单选题"}
                      {qr.questionType === "multiple-choice" && "多选题"}
                      {qr.questionType === "fill-blank" && "填空题"}
                      {qr.questionType === "short-answer" && "简答题"}
                      {qr.questionType === "essay" && "论述题"}
                    </span>
                  </div>
                  <div className="flex items-center gap-md">
                    <span className="text-xs text-ink-muted">
                      得分：{qr.earnedScore}/{qr.maxScore}
                    </span>
                    <span
                      className={cn(
                        "rounded px-sm py-xs text-xs font-medium",
                        qr.isCorrect && "bg-success/10 text-success",
                        !qr.isCorrect &&
                          qr.isAnswered &&
                          "bg-danger/10 text-danger",
                        !qr.isAnswered && "bg-ink-muted/10 text-ink-muted",
                      )}
                    >
                      {qr.isCorrect ? "正确" : qr.isAnswered ? "错误" : "未答"}
                    </span>
                  </div>
                </div>

                {/* 题目内容 */}
                <p className="mt-md text-sm text-ink">{qr.questionContent}</p>

                {/* 答案对比 */}
                <div className="mt-md space-y-sm">
                  <div className="flex gap-sm">
                    <span className="min-w-fit text-xs text-ink-muted">
                      你的答案：
                    </span>
                    <span
                      className={cn(
                        "text-sm",
                        qr.isCorrect ? "text-success" : "text-danger",
                      )}
                    >
                      {formatAnswer(qr.studentAnswer)}
                    </span>
                  </div>
                  {qr.correctAnswer && (
                    <div className="flex gap-sm">
                      <span className="min-w-fit text-xs text-ink-muted">
                        正确答案：
                      </span>
                      <span className="text-sm text-success">
                        {formatAnswer(qr.correctAnswer)}
                      </span>
                    </div>
                  )}
                </div>

                {/* 解析 */}
                {qr.explanation && (
                  <div className="mt-md rounded border border-rule bg-accent-muted/30 p-md">
                    <p className="text-xs text-ink-muted">解析</p>
                    <p className="mt-xs text-sm text-ink">{qr.explanation}</p>
                  </div>
                )}

                {/* 教师批注 */}
                <TeacherAnnotationOverlay
                  questionId={qr.questionId}
                  answerText={
                    qr.studentAnswer?.type === "short-answer" ||
                    qr.studentAnswer?.type === "essay"
                      ? qr.studentAnswer.text
                      : undefined
                  }
                  annotations={MOCK_ANNOTATIONS}
                />
              </div>
            ))}
          </div>
        </div>

        {/* === 操作按钮 === */}
        <div className="mt-xl flex justify-center gap-md">
          <button
            type="button"
            onClick={() => router.push("/my-exams")}
            className="rounded border border-rule px-xl py-sm text-sm text-ink hover:bg-accent-muted"
          >
            返回考试列表
          </button>
          <button
            type="button"
            onClick={() => router.push("/dashboard")}
            className="rounded bg-accent px-xl py-sm text-sm text-paper hover:bg-accent-hover"
          >
            返回首页
          </button>
        </div>
      </div>
    </div>
  );
}
