// 考试结果详情页面（家长查看子女考试结果）
// 依据：02-architecture-design.md §3.1 路由结构
// 路由：/parent/exams/[id]/result
// 对标 student-portal /my-exams/[id]/result（家长只读视角）

"use client";

import { useParams } from "next/navigation";
import { useChildExamResult } from "@/hooks/useChildExamResult";
import { useChildSwitcher } from "@/hooks/useChildSwitcher";
import { cn } from "@/lib/utils";
import type {
  AnswerInput,
  ExamResultSummary,
  QuestionResult,
  QuestionType,
} from "@/types";

const QUESTION_TYPE_LABELS: Record<QuestionType, string> = {
  "single-choice": "单选题",
  "multiple-choice": "多选题",
  "fill-blank": "填空题",
  "short-answer": "简答题",
  essay: "论述题",
};

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(":");
}

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 };
}

export default function ExamResultPage(): JSX.Element {
  const params = useParams();
  const examId =
    typeof params?.id === "string"
      ? params.id
      : Array.isArray(params?.id)
        ? (params.id[0] ?? "")
        : "";
  const { currentChild } = useChildSwitcher();
  const { result, loading, error } = useChildExamResult(examId);

  if (loading) {
    return (
      <div className="space-y-4" role="status" aria-live="polite">
        <span className="skeleton h-8 w-64 rounded" aria-hidden="true" />
        <span className="skeleton h-40 w-full rounded" aria-hidden="true" />
        <span className="skeleton h-64 w-full rounded" aria-hidden="true" />
        <span className="sr-only">加载考试结果中...</span>
      </div>
    );
  }

  if (error) {
    return (
      <div
        role="alert"
        className="rounded border border-danger p-4 text-sm text-danger"
      >
        加载失败：{error.message}
      </div>
    );
  }

  if (!result) {
    return (
      <p className="text-sm text-ink-muted" role="status">
        暂无考试结果数据
      </p>
    );
  }

  const summary = computeSummary(result.questionResults);
  const scorePercentage = Math.round((result.score / result.maxScore) * 100);
  const scoreTone =
    scorePercentage >= 80
      ? "text-success"
      : scorePercentage >= 60
        ? "text-warning"
        : "text-danger";

  return (
    <div className="space-y-6">
      <h1 className="font-serif text-2xl">{currentChild?.name}的考试结果</h1>

      {/* 结果概要 */}
      <div className="rounded border border-rule bg-paper-elevated p-4">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="font-serif text-base">{result.examName}</h2>
            <p className="mt-1 text-xs text-ink-muted">
              提交时间：{new Date(result.submittedAt).toLocaleString("zh-CN")}
            </p>
            <p className="mt-1 text-xs text-ink-muted">
              用时：{formatDuration(result.durationSeconds)}
            </p>
          </div>
          <div className="text-right">
            <div className={cn("font-mono text-3xl", scoreTone)}>
              {result.score}
              <span className="text-base text-ink-muted">
                /{result.maxScore}
              </span>
            </div>
            <div className={cn("mt-1 text-sm font-medium", scoreTone)}>
              {result.grade} · {scorePercentage}%
            </div>
          </div>
        </div>
      </div>

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

      {/* 逐题回顾 */}
      <div>
        <h2 className="font-serif text-base">逐题回顾</h2>
        <div className="mt-3 space-y-3">
          {result.questionResults.map((qr, idx) => (
            <QuestionReview key={qr.questionId} qr={qr} index={idx} />
          ))}
        </div>
      </div>
    </div>
  );
}

function QuestionReview({
  qr,
  index,
}: {
  qr: QuestionResult;
  index: number;
}): JSX.Element {
  const statusLabel = qr.isCorrect ? "正确" : qr.isAnswered ? "错误" : "未答";
  const statusTone = qr.isCorrect
    ? "text-success"
    : qr.isAnswered
      ? "text-danger"
      : "text-ink-muted";

  return (
    <div className="rounded border border-rule bg-paper-elevated p-4">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <span className="font-mono text-xs text-ink-muted">
            第 {index + 1} 题
          </span>
          <span className="text-xs text-ink-muted">
            {QUESTION_TYPE_LABELS[qr.questionType]}
          </span>
        </div>
        <div className="flex items-center gap-3">
          <span className="text-xs text-ink-muted">
            得分：{qr.earnedScore}/{qr.maxScore}
          </span>
          <span className={cn("text-xs font-medium", statusTone)}>
            {statusLabel}
          </span>
        </div>
      </div>

      <p className="mt-2 text-sm">{qr.questionContent}</p>

      <div className="mt-2 space-y-1">
        <div className="flex gap-2">
          <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-2">
            <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-2 rounded border border-rule bg-accent-soft p-2">
          <p className="text-xs text-ink-muted">解析</p>
          <p className="mt-1 text-sm">{qr.explanation}</p>
        </div>
      )}
    </div>
  );
}
