"use client";

/**
 * 考试详情页 - 显示考试基本信息 + 题目列表
 *
 * 数据来源（contract.md §2.4）：GraphQL ExamDetailQuery（P3 扩展，MSW mock）
 * - 动态路由 /exams/[id]，id 为考试 UUID
 * - DRAFT 状态展示"发布考试"按钮（调用 CreateExamMutation 复用为发布动作占位）
 *
 * 维护者：ai13（teacher-portal）
 */

import { useQuery, useMutation } from "urql";
import { useParams, useRouter } from "next/navigation";
import Link from "next/link";
import { useState } from "react";
import { Loading, Empty } from "@edu/ui-components";
import { ExamDetailQuery, CreateExamMutation } from "@/lib/graphql";
import type { ExamQuestion } from "@/lib/graphql";

/** 题目类型中文映射 */
const QUESTION_TYPE_LABEL: Record<ExamQuestion["type"], string> = {
  SINGLE_CHOICE: "单选题",
  MULTIPLE_CHOICE: "多选题",
  SHORT_ANSWER: "简答题",
  ESSAY: "论述题",
};

/** 考试状态中文映射 */
const EXAM_STATUS_LABEL: Record<string, string> = {
  DRAFT: "草稿",
  PUBLISHED: "已发布",
  IN_PROGRESS: "进行中",
  GRADING: "批改中",
  SCORED: "已完成",
  ARCHIVED: "已归档",
};

export default function ExamDetailPage() {
  const params = useParams<{ id: string }>();
  const router = useRouter();
  const examId = params?.id ?? "";

  const [result] = useQuery({
    query: ExamDetailQuery,
    variables: { id: examId },
    pause: !examId,
  });

  const [publishResult, publishExam] = useMutation(CreateExamMutation);
  const [publishing, setPublishing] = useState(false);
  const [publishError, setPublishError] = useState<string | null>(null);

  const handlePublish = async () => {
    if (!result.data?.examDetail) return;
    setPublishing(true);
    setPublishError(null);
    // 复用 CreateExamMutation 作为发布动作占位（MSW mock 接受相同 input）
    const res = await publishExam({
      input: {
        classId: result.data.examDetail.classId,
        title: result.data.examDetail.title,
        description: result.data.examDetail.description,
        examDate: result.data.examDetail.examDate,
        duration: result.data.examDetail.duration,
        totalScore: result.data.examDetail.totalScore,
      },
    });
    setPublishing(false);
    if (res.error) {
      setPublishError(res.error.message);
      return;
    }
    // 发布成功后回到考试列表
    router.push(`/exams?classId=${result.data.examDetail.classId}`);
  };

  return (
    <div className="px-10 py-10">
      <header className="mb-8">
        <p className="mb-2">
          <Link
            href={`/exams?classId=${result.data?.examDetail?.classId ?? ""}`}
            className="text-tiny uppercase tracking-wide text-ink-muted hover:opacity-70"
          >
            ← 返回考试列表
          </Link>
        </p>
        <h1 className="text-3xl font-serif text-ink">考试详情</h1>
        <p className="mt-1 text-sm text-ink-muted">
          GraphQL ExamDetailQuery · core-edu 域（P3 扩展，MSW mock）
        </p>
      </header>

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

      {result.fetching ? (
        <Loading lines={6} />
      ) : result.error ? (
        <div className="mark-left mb-4 py-2 border-l-2 border-danger pl-md">
          <p className="text-sm px-3 text-danger">
            加载失败：{result.error.message}
          </p>
        </div>
      ) : !result.data?.examDetail ? (
        <Empty title="未找到考试" description="该考试不存在或已被删除" />
      ) : (
        <section className="max-w-4xl">
          {/* 基本信息 */}
          <div className="mb-10">
            <h2 className="text-xl font-serif text-ink mb-2">
              {result.data.examDetail.title}
            </h2>
            {result.data.examDetail.description && (
              <p className="mt-1 text-sm text-ink-muted">
                {result.data.examDetail.description}
              </p>
            )}
            <div className="rule-thin mb-4 mt-3" />
            <dl className="grid grid-cols-2 gap-4 text-sm">
              <div>
                <dt className="text-tiny uppercase tracking-wide text-ink-muted">
                  考试时间
                </dt>
                <dd className="mt-1 text-ink">
                  {new Date(result.data.examDetail.examDate).toLocaleString("zh-CN")}
                </dd>
              </div>
              <div>
                <dt className="text-tiny uppercase tracking-wide text-ink-muted">
                  时长
                </dt>
                <dd className="mt-1 text-ink">
                  {result.data.examDetail.duration} 分钟
                </dd>
              </div>
              <div>
                <dt className="text-tiny uppercase tracking-wide text-ink-muted">
                  满分
                </dt>
                <dd className="mt-1 text-ink">
                  {result.data.examDetail.totalScore} 分
                </dd>
              </div>
              <div>
                <dt className="text-tiny uppercase tracking-wide text-ink-muted">
                  状态
                </dt>
                <dd className="mt-1 text-ink">
                  {EXAM_STATUS_LABEL[result.data.examDetail.status] ?? result.data.examDetail.status}
                  {result.data.examDetail.status === "DRAFT" && (
                    <span className="ml-2 text-tiny text-warning">未发布</span>
                  )}
                </dd>
              </div>
            </dl>

            {/* 发布按钮（仅 DRAFT 状态可见） */}
            {result.data.examDetail.status === "DRAFT" && (
              <div className="mt-6">
                <button
                  type="button"
                  onClick={handlePublish}
                  disabled={publishing}
                  className="px-4 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover disabled:opacity-50"
                >
                  {publishing ? "发布中..." : "发布考试"}
                </button>
                {publishError && (
                  <p className="mt-2 text-tiny text-danger">
                    发布失败：{publishError}
                  </p>
                )}
                {publishResult.data && !publishError && (
                  <p className="mt-2 text-tiny text-success">发布成功</p>
                )}
              </div>
            )}
          </div>

          {/* 题目列表 */}
          <div>
            <div className="flex items-baseline justify-between mb-4">
              <h3 className="text-xl font-serif text-ink">
                题目列表
                <span className="ml-2 text-sm font-sans text-ink-muted">
                  {result.data.examDetail.questions.length} 题
                </span>
              </h3>
            </div>
            <div className="rule-thin mb-6" />

            {result.data.examDetail.questions.length === 0 ? (
              <Empty title="暂无题目" description="该考试尚未添加题目" />
            ) : (
              <ol className="space-y-0">
                {result.data.examDetail.questions.map((q: ExamQuestion) => (
                  <li
                    key={q.id}
                    className="py-4 grid grid-cols-12 gap-4 items-baseline border-b border-rule"
                  >
                    <div className="col-span-1 text-tiny font-mono text-ink-muted">
                      {q.order}.
                    </div>
                    <div className="col-span-7">
                      <h4 className="text-base font-serif text-ink">
                        {q.title}
                      </h4>
                      <p className="mt-1 text-tiny text-ink-muted">
                        类型：{QUESTION_TYPE_LABEL[q.type]}
                      </p>
                    </div>
                    <div className="col-span-2 text-sm text-ink">
                      {q.score} 分
                    </div>
                    <div className="col-span-2 text-right text-tiny font-mono text-ink-muted">
                      {q.id.slice(0, 8)}...
                    </div>
                  </li>
                ))}
              </ol>
            )}
          </div>
        </section>
      )}
    </div>
  );
}
