"use client";

/**
 * MyExams — 我的考试列表（ai14）
 *
 * 数据源：useMyExams GraphQL hook
 * 视图：按状态分组（not_started / in_progress / submitted / graded）
 *      每张卡片：标题 + 学科 + 起止时间 + 时长 + 状态徽标
 * 链接：active（in_progress）→ /my-exams/[id]/take
 *      submitted/graded → /my-exams/[id]/result
 *
 * 设计依据：01-understanding.md §8（L2 路由表）
 *          02-architecture-design.md §11（考试作答边界场景）
 */

import Link from "next/link";
import { useMyExams } from "@/lib/graphql/hooks";
import type { ExamListItem, ExamStatus } from "@/lib/graphql/types";

const dateFormatter = new Intl.DateTimeFormat("zh-CN", {
  month: "2-digit",
  day: "2-digit",
  hour: "2-digit",
  minute: "2-digit",
});

// 状态分组配置（顺序即展示顺序）
const STATUS_GROUPS: Array<{
  key: ExamStatus;
  label: string;
  description: string;
}> = [
  {
    key: "in_progress",
    label: "进行中",
    description: "点击进入作答",
  },
  {
    key: "not_started",
    label: "未开始",
    description: "等待开考",
  },
  {
    key: "submitted",
    label: "已提交",
    description: "等待批改",
  },
  {
    key: "graded",
    label: "已批改",
    description: "查看成绩",
  },
  {
    key: "expired",
    label: "已结束",
    description: "考试已结束",
  },
];

export default function MyExamsPage(): JSX.Element {
  const { data, fetching, error } = useMyExams();
  const exams = data ?? [];

  // 按状态分组
  const grouped = STATUS_GROUPS.map((g) => ({
    ...g,
    items: exams.filter((e) => e.status === g.key),
  }));

  return (
    <div className="px-6 lg:px-10 py-8 lg:py-10 max-w-7xl 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)" }}
        >
          我的考试
        </h1>
        <p className="mt-2 text-sm" style={{ color: "var(--color-ink-muted)" }}>
          按状态查看所有考试，进行中的考试可直接进入作答。
        </p>
      </header>

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

      {fetching ? (
        <LoadingSkeleton />
      ) : error ? (
        <ErrorState message={error.message} />
      ) : exams.length === 0 ? (
        <EmptyState />
      ) : (
        <div className="space-y-10">
          {grouped.map(
            (group) =>
              group.items.length > 0 && (
                <section key={group.key} aria-label={group.label}>
                  <div className="flex items-baseline gap-3 mb-4">
                    <h2
                      className="text-lg font-serif"
                      style={{ color: "var(--color-ink)" }}
                    >
                      {group.label}
                    </h2>
                    <span
                      className="text-xs"
                      style={{ color: "var(--color-ink-muted)" }}
                    >
                      {group.items.length} 场 · {group.description}
                    </span>
                  </div>
                  <div className="rule-thin mb-4" />
                  <ul className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                    {group.items.map((exam) => (
                      <li key={exam.id}>
                        <ExamCard exam={exam} />
                      </li>
                    ))}
                  </ul>
                </section>
              ),
          )}
        </div>
      )}
    </div>
  );
}

function ExamCard({ exam }: { exam: ExamListItem }): JSX.Element {
  const startsAt = new Date(exam.startsAt);
  const isTakeable = exam.status === "in_progress";
  const isResult = exam.status === "submitted" || exam.status === "graded";

  const linkHref = isTakeable
    ? `/my-exams/${exam.id}/take`
    : isResult
      ? `/my-exams/${exam.id}/result`
      : null;

  const badgeClass = getBadgeClassForStatus(exam.status);

  const inner = (
    <article
      className={`card-paper p-5 h-full transition-shadow ${
        linkHref ? "hover:shadow-card motion-safe" : ""
      }`}
      aria-label={`${exam.name} - ${exam.status}`}
    >
      <div className="flex items-start justify-between gap-3">
        <div className="min-w-0 flex-1">
          <p
            className="text-xs uppercase tracking-wider"
            style={{ color: "var(--color-ink-muted)" }}
          >
            {exam.subject.name}
          </p>
          <h3
            className="mt-1 text-lg font-serif text-truncate"
            style={{ color: "var(--color-ink)" }}
          >
            {exam.name}
          </h3>
        </div>
        <span className={`badge ${badgeClass} flex-shrink-0`}>
          {getStatusLabel(exam.status)}
        </span>
      </div>

      <div className="rule-thin my-4" />

      <dl className="grid grid-cols-2 gap-y-2 text-xs">
        <div>
          <dt
            className="uppercase tracking-wider"
            style={{ color: "var(--color-ink-muted)" }}
          >
            开考时间
          </dt>
          <dd className="mt-1" style={{ color: "var(--color-ink)" }}>
            {dateFormatter.format(startsAt)}
          </dd>
        </div>
        <div>
          <dt
            className="uppercase tracking-wider"
            style={{ color: "var(--color-ink-muted)" }}
          >
            时长
          </dt>
          <dd className="mt-1" style={{ color: "var(--color-ink)" }}>
            {Math.round(exam.durationSeconds / 60)} 分钟
          </dd>
        </div>
        <div>
          <dt
            className="uppercase tracking-wider"
            style={{ color: "var(--color-ink-muted)" }}
          >
            题量
          </dt>
          <dd className="mt-1" style={{ color: "var(--color-ink)" }}>
            {exam.questionCount} 题
          </dd>
        </div>
        <div>
          <dt
            className="uppercase tracking-wider"
            style={{ color: "var(--color-ink-muted)" }}
          >
            满分
          </dt>
          <dd className="mt-1" style={{ color: "var(--color-ink)" }}>
            {exam.totalScore} 分
          </dd>
        </div>
      </dl>

      {linkHref && (
        <p className="mt-4 text-xs" style={{ color: "var(--color-accent)" }}>
          {isTakeable ? "进入作答 →" : "查看结果 →"}
        </p>
      )}
    </article>
  );

  if (!linkHref) return inner;
  return (
    <Link
      href={linkHref}
      className="block h-full focus-visible:outline-2"
      aria-label={`${exam.name} - ${isTakeable ? "进入作答" : "查看结果"}`}
    >
      {inner}
    </Link>
  );
}

function getBadgeClassForStatus(status: ExamStatus): string {
  switch (status) {
    case "in_progress":
      return "badge-danger";
    case "not_started":
      return "badge-info";
    case "submitted":
      return "badge-warning";
    case "graded":
      return "badge-success";
    case "expired":
      return "badge-info";
    default:
      return "badge-info";
  }
}

function getStatusLabel(status: ExamStatus): string {
  const map: Record<ExamStatus, string> = {
    not_started: "未开始",
    in_progress: "进行中",
    submitted: "已提交",
    graded: "已批改",
    expired: "已结束",
  };
  return map[status] ?? status;
}

function LoadingSkeleton(): JSX.Element {
  return (
    <div aria-busy="true" aria-live="polite" className="space-y-10">
      {[0, 1].map((i) => (
        <div key={i} aria-hidden="true">
          <div
            className="h-4 w-24 rounded-sm animate-pulse mb-4"
            style={{ background: "var(--color-rule)" }}
          />
          <div className="rule-thin mb-4" />
          <ul className="grid grid-cols-1 lg:grid-cols-2 gap-4">
            {[0, 1].map((j) => (
              <li key={j} className="card-paper p-5">
                <div
                  className="h-3 w-16 rounded-sm animate-pulse"
                  style={{ background: "var(--color-rule)" }}
                />
                <div
                  className="mt-2 h-5 w-32 rounded-sm animate-pulse"
                  style={{ background: "var(--color-rule)" }}
                />
                <div
                  className="mt-6 h-px w-full"
                  style={{ background: "var(--color-rule)" }}
                />
                <div className="mt-4 grid grid-cols-2 gap-y-3">
                  {[0, 1, 2, 3].map((k) => (
                    <div
                      key={k}
                      className="h-3 w-20 rounded-sm animate-pulse"
                      style={{ background: "var(--color-rule)" }}
                    />
                  ))}
                </div>
              </li>
            ))}
          </ul>
        </div>
      ))}
      <span className="sr-only">正在加载考试列表...</span>
    </div>
  );
}

function ErrorState({ message }: { message: string }): JSX.Element {
  return (
    <div
      role="alert"
      className="card-paper p-8 text-center"
      style={{ borderColor: "var(--color-danger)" }}
    >
      <p
        className="text-base font-serif"
        style={{ color: "var(--color-danger)" }}
      >
        考试列表加载失败
      </p>
      <p className="mt-2 text-sm" style={{ color: "var(--color-ink-muted)" }}>
        {message}
      </p>
      <button
        type="button"
        onClick={() => window.location.reload()}
        className="mt-4 btn-secondary text-xs"
      >
        重新加载
      </button>
    </div>
  );
}

function EmptyState(): JSX.Element {
  return (
    <div className="card-paper p-8 text-center">
      <p
        className="text-4xl font-serif"
        style={{ color: "var(--color-ink-subtle)" }}
        aria-hidden="true"
      >
        ✎
      </p>
      <p
        className="mt-4 text-base font-serif"
        style={{ color: "var(--color-ink)" }}
      >
        暂无考试安排
      </p>
      <p className="mt-2 text-sm" style={{ color: "var(--color-ink-muted)" }}>
        当老师发布考试后，这里会显示考试日程与作答入口。
      </p>
    </div>
  );
}
