"use client";

/**
 * Exams 页面 - 考试管理
 *
 * 数据来源（contract.md §2.4）：GraphQL ClassExamsQuery（P3 扩展，MSW mock）
 * - 通过 URL ?classId=xxx 指定班级
 * - P2 阶段用 MSW mock 数据，待 teacher-bff P3 启用 core-edu 聚合
 * - P3：列表项可点击进入详情页，顶部提供"新建考试"入口
 *
 * 维护者：ai13（teacher-portal）
 */

import { useQuery } from "urql";
import { useSearchParams } from "next/navigation";
import Link from "next/link";
import { Suspense } from "react";
import { Loading, Empty } from "@edu/ui-components";
import { ClassExamsQuery, ClassQuery } from "@/lib/graphql";
import type { ExamItem } from "@/lib/graphql";

function ExamsContent() {
  const searchParams = useSearchParams();
  const classId = searchParams.get("classId") ?? "";

  const [classResult] = useQuery({
    query: ClassQuery,
    variables: { id: classId },
    pause: !classId,
  });

  const [examsResult] = useQuery({
    query: ClassExamsQuery,
    variables: { classId },
    pause: !classId,
  });

  if (!classId) {
    return (
      <div className="px-10 py-10">
        <Empty title="未指定班级" description="请从班级列表进入查看考试" />
      </div>
    );
  }

  const cls = classResult.data?.class;
  const exams = examsResult.data?.classExams ?? [];

  return (
    <div className="px-10 py-10">
      <header className="mb-8 flex items-baseline justify-between">
        <div>
          <h1 className="text-3xl font-serif text-ink">
            {cls ? `${cls.name} - 考试管理` : "考试管理"}
          </h1>
          <p className="mt-1 text-sm text-ink-muted">
            GraphQL ClassExamsQuery · core-edu 域（P3 扩展，MSW mock）
          </p>
        </div>
        <Link
          href={`/exams/new?classId=${classId}`}
          className="px-4 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover"
        >
          新建考试
        </Link>
      </header>

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

      {examsResult.fetching ? (
        <Loading lines={4} />
      ) : examsResult.error ? (
        <div className="mark-left mb-4 py-2 border-l-2 border-danger pl-md">
          <p className="text-sm px-3 text-danger">
            加载失败：{examsResult.error.message}
          </p>
        </div>
      ) : exams.length === 0 ? (
        <Empty
          title="暂无考试"
          description="该班级尚未创建考试"
          action={
            <Link
              href={`/exams/new?classId=${classId}`}
              className="px-4 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover"
            >
              创建第一场考试
            </Link>
          }
        />
      ) : (
        <ul className="space-y-0">
          {(exams as ExamItem[]).map((exam) => (
            <li
              key={exam.id}
              className="py-4 grid grid-cols-12 gap-4 items-baseline border-b border-rule hover:bg-subtle"
            >
              <div className="col-span-7">
                <Link href={`/exams/${exam.id}`}>
                  <h3 className="text-lg font-serif text-ink hover:text-accent">
                    {exam.title}
                  </h3>
                </Link>
                {exam.description && (
                  <p className="mt-1 text-sm text-ink-muted">
                    {exam.description}
                  </p>
                )}
                <p className="mt-1 text-tiny text-ink-muted">
                  考试时间: {new Date(exam.examDate).toLocaleString("zh-CN")}
                  {" · "}时长 {exam.duration} 分钟
                  {" · "}满分 {exam.totalScore}
                </p>
              </div>
              <div className="col-span-3 text-tiny text-ink-muted">
                状态: {exam.status}
              </div>
              <div className="col-span-2 text-right text-tiny">
                <Link
                  href={`/exams/${exam.id}`}
                  className="font-mono text-ink-muted hover:text-accent"
                >
                  查看详情 →
                </Link>
              </div>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

export default function ExamsPage() {
  return (
    <Suspense
      fallback={
        <div className="px-10 py-10">
          <Loading lines={3} />
        </div>
      }
    >
      <ExamsContent />
    </Suspense>
  );
}
