"use client";

/**
 * ElectiveDetail — 选课详情（批次 A）
 *
 * 数据源：useAvailableElectiveCourses（按 id 过滤）
 *         + useMyElectiveSelections + useSelectElectiveCourse + useDropElectiveCourse
 */

import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import {
  useAvailableElectiveCourses,
  useMyElectiveSelections,
  useSelectElectiveCourse,
  useDropElectiveCourse,
} from "@/lib/graphql/hooks";
import type { ElectiveCourseStatus } from "@/lib/graphql/types";

const COURSE_STATUS_LABELS: Record<ElectiveCourseStatus, string> = {
  draft: "草稿",
  open: "开放选课",
  closed: "已截止",
  cancelled: "已取消",
};

export default function ElectiveDetailPage(): JSX.Element {
  const params = useParams();
  const router = useRouter();
  const courseId = params["id"] as string;

  const { data: courses, fetching, error } = useAvailableElectiveCourses();
  const { data: selections, reexecute: reexecuteSel } = useMyElectiveSelections();
  const { execute: selectExecute, fetching: selectFetching } = useSelectElectiveCourse();
  const { execute: dropExecute, fetching: dropFetching } = useDropElectiveCourse();

  const course = (courses ?? []).find((c) => c.id === courseId) ?? null;
  const mySelection = (selections ?? []).find((s) => s.courseId === courseId) ?? null;
  const isEnrolled = mySelection?.status === "enrolled" || mySelection?.status === "selected";

  const handleSelect = (): void => {
    selectExecute({ courseId });
    reexecuteSel();
  };

  const handleDrop = (): void => {
    dropExecute({ courseId });
    reexecuteSel();
  };

  if (fetching) {
    return (
      <div className="px-6 lg:px-10 py-8 max-w-4xl mx-auto">
        <p className="text-sm" style={{ color: "var(--color-ink-muted)" }} aria-live="polite">
          加载中…
        </p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="px-6 lg:px-10 py-8 max-w-4xl mx-auto">
        <div role="alert" className="card-paper p-6" style={{ borderColor: "var(--color-danger)" }}>
          <p className="text-sm" style={{ color: "var(--color-danger)" }}>
            课程加载失败：{error.message}
          </p>
          <button type="button" onClick={() => router.back()} className="mt-4 btn-secondary text-xs">
            返回
          </button>
        </div>
      </div>
    );
  }

  if (!course) {
    return (
      <div className="px-6 lg:px-10 py-8 max-w-4xl mx-auto">
        <div className="card-paper p-8 text-center">
          <p className="text-base font-serif" style={{ color: "var(--color-ink)" }}>
            未找到该课程
          </p>
          <Link href="/elective" className="mt-4 inline-block btn-secondary text-xs">
            返回选课中心
          </Link>
        </div>
      </div>
    );
  }

  const fillRate = course.capacity > 0 ? course.enrolledCount / course.capacity : 0;
  const isFull = course.enrolledCount >= course.capacity;

  return (
    <div className="px-6 lg:px-10 py-8 lg:py-10 max-w-4xl mx-auto">
      <Link
        href="/elective"
        className="text-xs"
        style={{ color: "var(--color-ink-muted)" }}
      >
        ← 返回选课中心
      </Link>

      <header className="mt-4 mb-6">
        <div className="flex items-center gap-2 mb-2">
          <span className="badge badge-info">{course.subjectName ?? "—"}</span>
          <span className={`badge ${course.status === "open" ? "badge-success" : "badge-warning"}`}>
            {COURSE_STATUS_LABELS[course.status]}
          </span>
          <span className="text-xs" style={{ color: "var(--color-ink-muted)" }}>
            {course.selectionMode === "fcfs" ? "先到先得" : "抽签"}
          </span>
        </div>
        <h1 className="text-3xl font-serif" style={{ color: "var(--color-ink)" }}>
          {course.name}
        </h1>
      </header>

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

      {course.description && (
        <section className="mb-6">
          <h2 className="text-sm uppercase tracking-wider mb-2" style={{ color: "var(--color-ink-muted)" }}>
            课程简介
          </h2>
          <p className="text-sm" style={{ color: "var(--color-ink)" }}>
            {course.description}
          </p>
        </section>
      )}

      <section className="card-paper p-6 mb-6">
        <dl className="grid grid-cols-2 gap-4 text-sm">
          <div>
            <dt className="text-xs uppercase tracking-wider" style={{ color: "var(--color-ink-muted)" }}>
              授课教师
            </dt>
            <dd className="mt-1" style={{ color: "var(--color-ink)" }}>{course.teacherName ?? "—"}</dd>
          </div>
          <div>
            <dt className="text-xs uppercase tracking-wider" style={{ color: "var(--color-ink-muted)" }}>
              上课教室
            </dt>
            <dd className="mt-1" style={{ color: "var(--color-ink)" }}>{course.classroom ?? "—"}</dd>
          </div>
          <div>
            <dt className="text-xs uppercase tracking-wider" style={{ color: "var(--color-ink-muted)" }}>
              上课时间
            </dt>
            <dd className="mt-1" style={{ color: "var(--color-ink)" }}>{course.schedule ?? "—"}</dd>
          </div>
          <div>
            <dt className="text-xs uppercase tracking-wider" style={{ color: "var(--color-ink-muted)" }}>
              学分
            </dt>
            <dd className="mt-1" style={{ color: "var(--color-ink)" }}>{course.credit}</dd>
          </div>
          <div>
            <dt className="text-xs uppercase tracking-wider" style={{ color: "var(--color-ink-muted)" }}>
              课程周期
            </dt>
            <dd className="mt-1" style={{ color: "var(--color-ink)" }}>
              {course.startDate ?? "—"} 至 {course.endDate ?? "—"}
            </dd>
          </div>
          <div>
            <dt className="text-xs uppercase tracking-wider" style={{ color: "var(--color-ink-muted)" }}>
              年级
            </dt>
            <dd className="mt-1" style={{ color: "var(--color-ink)" }}>{course.gradeName ?? "—"}</dd>
          </div>
        </dl>
      </section>

      <section className="card-paper p-6 mb-6">
        <div className="flex items-center justify-between gap-4">
          <div>
            <p className="text-xs uppercase tracking-wider" style={{ color: "var(--color-ink-muted)" }}>
              容量
            </p>
            <p className="mt-1 text-2xl font-serif" style={{ color: "var(--color-ink)" }}>
              {course.enrolledCount}<span className="text-sm" style={{ color: "var(--color-ink-muted)" }}>/{course.capacity}</span>
            </p>
          </div>
          <div className="flex-1 max-w-xs h-2 rounded-sm overflow-hidden" style={{ background: "var(--color-rule)" }}>
            <div
              className="h-full"
              style={{
                width: `${Math.min(fillRate * 100, 100)}%`,
                background: isFull ? "var(--color-danger)" : "var(--color-accent)",
              }}
            />
          </div>
        </div>
      </section>

      {course.selectionStartAt && course.selectionEndAt && (
        <section className="card-paper p-6 mb-6">
          <h2 className="text-sm uppercase tracking-wider mb-2" style={{ color: "var(--color-ink-muted)" }}>
            选课时间
          </h2>
          <p className="text-sm" style={{ color: "var(--color-ink)" }}>
            {new Date(course.selectionStartAt).toLocaleString("zh-CN")} 至{" "}
            {new Date(course.selectionEndAt).toLocaleString("zh-CN")}
          </p>
          {course.dropDeadline && (
            <p className="mt-1 text-xs" style={{ color: "var(--color-ink-muted)" }}>
              退选截止：{new Date(course.dropDeadline).toLocaleString("zh-CN")}
            </p>
          )}
        </section>
      )}

      <div className="flex gap-3">
        {course.status === "open" && !isEnrolled && (
          <button
            type="button"
            onClick={handleSelect}
            disabled={isFull || selectFetching}
            className="btn-primary text-sm disabled:opacity-50"
          >
            {selectFetching ? "选课中..." : isFull ? "已满" : "选课"}
          </button>
        )}
        {isEnrolled && (
          <button
            type="button"
            onClick={handleDrop}
            disabled={dropFetching}
            className="btn-secondary text-sm disabled:opacity-50"
          >
            {dropFetching ? "退选中..." : "退选"}
          </button>
        )}
      </div>
    </div>
  );
}
