"use client";

/**
 * AssignmentAnalysis — 作业分析（ai14，P5，路由 /my-homework/[id]/analysis）
 *
 * 数据源：useAssignmentAnalysis GraphQL hook
 * 视图：
 * - 汇总统计（平均分、最高分、最低分、提交人数）
 * - 题目分析列表（正确率、参考答案、知识点）
 * - 正确率进度条可视化
 *
 * 设计依据：纸感设计（card-paper + mark-left 知识点标签）
 */

import { useParams } from "next/navigation";
import { useAssignmentAnalysis } from "@/lib/graphql/hooks";
import type { AssignmentAnalysisQuestion } from "@/lib/graphql/types";

/** 正确率对应的颜色令牌 */
function correctRateColor(rate: number): string {
  if (rate >= 0.8) return "var(--color-success)";
  if (rate >= 0.6) return "var(--color-warning)";
  return "var(--color-danger)";
}

/** 正确率标签 */
function correctRateLabel(rate: number): string {
  const percent = Math.round(rate * 100);
  return `${percent}%`;
}

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

export default function AssignmentAnalysisPage(): JSX.Element {
  const params = useParams();
  const homeworkId = String(params?.id ?? "");
  const { data, fetching, error, reexecute } = useAssignmentAnalysis(homeworkId);

  return (
    <div className="px-6 lg:px-10 py-8 lg:py-10 max-w-4xl mx-auto">
      <header className="mb-6">
        <p
          className="text-xs uppercase tracking-wider"
          style={{ color: "var(--color-ink-muted)" }}
        >
          作业分析
        </p>
        <h1
          className="mt-2 text-3xl lg:text-4xl font-serif"
          style={{ color: "var(--color-ink)" }}
        >
          {data?.title ?? "作业分析"}
        </h1>
        <p
          className="mt-2 text-sm"
          style={{ color: "var(--color-ink-muted)" }}
        >
          查看本次作业的班级整体作答情况、正确率与参考答案。
        </p>
      </header>

      <div className="rule-thin mb-6" />

      {fetching ? (
        <p
          className="text-sm"
          style={{ color: "var(--color-ink-muted)" }}
          aria-live="polite"
        >
          加载中…
        </p>
      ) : error ? (
        <div className="mark-left py-md px-md mb-md" aria-live="assertive">
          <p
            className="text-sm"
            style={{ color: "var(--color-ink)" }}
          >
            {error.message || "加载失败"}
          </p>
          <button
            type="button"
            className="btn-secondary mt-sm"
            onClick={() => reexecute()}
          >
            重试
          </button>
        </div>
      ) : !data ? (
        <p
          className="text-sm"
          style={{ color: "var(--color-ink-muted)" }}
          role="status"
        >
          暂无分析数据
        </p>
      ) : (
        <>
          {/* 汇总统计 */}
          <section
            className="grid grid-cols-2 sm:grid-cols-4 gap-md mb-lg"
            aria-label="作业汇总"
          >
            <StatCard label="总分" value={String(data.totalScore)} />
            <StatCard label="平均分" value={String(data.avgScore)} />
            <StatCard label="最高分" value={String(data.maxScore)} />
            <StatCard label="最低分" value={String(data.minScore)} />
          </section>

          <div
            className="mb-lg text-sm"
            style={{ color: "var(--color-ink-muted)" }}
          >
            提交人数：<span style={{ color: "var(--color-ink)" }}>{data.submitCount}</span> 人
          </div>

          {/* 题目分析列表 */}
          <section aria-label="题目分析">
            <h2
              className="font-serif text-lg mb-md"
              style={{ color: "var(--color-ink)" }}
            >
              逐题分析
            </h2>
            <div className="space-y-md">
              {data.questions.map((q, idx) => (
                <QuestionAnalysisCard
                  key={q.questionId}
                  question={q}
                  index={idx + 1}
                />
              ))}
            </div>
          </section>
        </>
      )}
    </div>
  );
}

/** 统计卡片 */
function StatCard({
  label,
  value,
}: {
  label: string;
  value: string;
}): JSX.Element {
  return (
    <div className="card-paper p-md">
      <p
        className="text-xs"
        style={{ color: "var(--color-ink-subtle)" }}
      >
        {label}
      </p>
      <p
        className="font-serif text-2xl mt-xs"
        style={{ color: "var(--color-ink)" }}
      >
        {value}
      </p>
    </div>
  );
}

/** 题目分析卡片 */
function QuestionAnalysisCard({
  question,
  index,
}: {
  question: AssignmentAnalysisQuestion;
  index: number;
}): JSX.Element {
  const rateColor = correctRateColor(question.correctRate);
  const ratePercent = Math.round(question.correctRate * 100);

  return (
    <div className="card-paper p-md">
      {/* 题目头部 */}
      <div className="flex items-start justify-between gap-md mb-sm">
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-sm mb-xs">
            <span
              className="font-serif text-sm"
              style={{ color: "var(--color-ink)" }}
            >
              第 {index} 题
            </span>
            <span
              className="badge badge-info"
            >
              {QUESTION_TYPE_LABELS[question.questionType] ?? question.questionType}
            </span>
          </div>
          <p
            className="text-sm"
            style={{ color: "var(--color-ink)" }}
          >
            {question.questionText}
          </p>
        </div>
        <div className="text-right flex-shrink-0">
          <p
            className="text-xs"
            style={{ color: "var(--color-ink-subtle)" }}
          >
            正确率
          </p>
          <p
            className="font-serif text-xl"
            style={{ color: rateColor }}
          >
            {correctRateLabel(question.correctRate)}
          </p>
        </div>
      </div>

      {/* 正确率进度条 */}
      <div
        className="w-full h-1.5 rounded-full overflow-hidden mb-md"
        style={{ background: "var(--color-rule)" }}
        role="progressbar"
        aria-valuenow={ratePercent}
        aria-valuemin={0}
        aria-valuemax={100}
        aria-label={`正确率 ${ratePercent}%`}
      >
        <div
          className="h-full rounded-full transition-all"
          style={{
            width: `${ratePercent}%`,
            background: rateColor,
          }}
        />
      </div>

      {/* 参考答案 */}
      <div className="mark-left">
        <p
          className="text-xs mb-xs"
          style={{ color: "var(--color-ink-muted)" }}
        >
          参考答案
        </p>
        <p
          className="text-sm leading-relaxed"
          style={{ color: "var(--color-ink)" }}
        >
          {question.referenceAnswer}
        </p>
      </div>

      {/* 知识点 */}
      {question.knowledgePoints.length > 0 && (
        <div className="mt-sm flex flex-wrap gap-xs">
          {question.knowledgePoints.map((kp) => (
            <span
              key={kp}
              className="badge badge-info"
            >
              {kp}
            </span>
          ))}
        </div>
      )}
    </div>
  );
}
