"use client";

/**
 * 课程详情页（ai14，P3）
 *
 * 数据源：useMyClasses（按 id 筛选）+ useMySchedule（班级课表）
 *
 * 视图模块：
 * - 教师信息卡：班主任姓名 + 学生人数
 * - 学业信息卡：年级 + 学年
 * - 教室信息：从课表中提取的去重教室列表
 * - 班级课表：周视图（周一到周五，按时间段排列，复用 schedule 页样式）
 *
 * 设计依据：纸感设计（card-paper + rule-thin + mark-left + serif 标题）
 */

import { useMemo } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { useMyClasses, useMySchedule } from "@/lib/graphql/hooks";
import type { ScheduleItem } from "@/lib/graphql/types";

const DAY_LABELS: Record<number, string> = {
  1: "周一",
  2: "周二",
  3: "周三",
  4: "周四",
  5: "周五",
  6: "周六",
  0: "周日",
};

const WEEKDAYS = [1, 2, 3, 4, 5];

/** 按天分组 */
function groupByDay(items: ScheduleItem[]): Map<number, ScheduleItem[]> {
  const map = new Map<number, ScheduleItem[]>();
  for (const item of items) {
    const list = map.get(item.dayOfWeek) ?? [];
    list.push(item);
    map.set(item.dayOfWeek, list);
  }
  for (const list of map.values()) {
    list.sort((a, b) => a.startTime.localeCompare(b.startTime));
  }
  return map;
}

export default function CourseDetailPage(): JSX.Element {
  const params = useParams();
  const classId = params["id"] as string;

  const { data: classesData, fetching: clsFetching, error: clsError } = useMyClasses();
  const { data: scheduleData, fetching: schedFetching, error: schedError } = useMySchedule();

  const cls = useMemo(
    () => classesData?.find((c) => c.id === classId) ?? null,
    [classesData, classId],
  );

  const scheduleItems = scheduleData ?? [];
  const grouped = useMemo(() => groupByDay(scheduleItems), [scheduleItems]);

  // 提取去重教室列表
  const classrooms = useMemo(() => {
    const set = new Set<string>();
    scheduleItems.forEach((s) => set.add(s.classroom));
    return Array.from(set);
  }, [scheduleItems]);

  // 提取去重教师列表
  const teachers = useMemo(() => {
    const set = new Set<string>();
    scheduleItems.forEach((s) => set.add(s.teacher));
    return Array.from(set);
  }, [scheduleItems]);

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

  if (clsError) {
    return (
      <div className="px-6 lg:px-10 py-8 lg:py-10 max-w-5xl mx-auto">
        <div
          role="alert"
          className="card-paper p-6"
          style={{ borderColor: "var(--color-danger)" }}
        >
          <p className="text-sm" style={{ color: "var(--color-danger)" }}>
            课程加载失败：{clsError.message}
          </p>
          <Link
            href="/courses"
            className="mt-4 inline-block btn-secondary text-xs"
          >
            返回课程列表
          </Link>
        </div>
      </div>
    );
  }

  if (!cls) {
    return (
      <div className="px-6 lg:px-10 py-8 lg:py-10 max-w-5xl mx-auto">
        <div className="card-paper p-8 text-center">
          <p
            className="text-base font-serif"
            style={{ color: "var(--color-ink)" }}
          >
            未找到该课程
          </p>
          <p
            className="mt-2 text-sm"
            style={{ color: "var(--color-ink-muted)" }}
          >
            可能你已退出该班级，或链接已失效。
          </p>
          <Link
            href="/courses"
            className="mt-4 inline-block btn-secondary text-xs"
          >
            返回课程列表
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="px-6 lg:px-10 py-8 lg:py-10 max-w-5xl mx-auto">
      <Link
        href="/courses"
        className="text-xs"
        style={{ color: "var(--color-ink-muted)" }}
      >
        ← 返回课程列表
      </Link>

      <header className="mt-3 mb-6">
        <p
          className="text-xs uppercase tracking-wider"
          style={{ color: "var(--color-ink-muted)" }}
        >
          {cls.grade} · {cls.year} 学年
        </p>
        <h1
          className="mt-2 text-3xl lg:text-4xl font-serif"
          style={{ color: "var(--color-ink)" }}
        >
          {cls.name}
        </h1>
      </header>

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

      {/* 信息卡片三宫格 */}
      <section
        aria-label="课程信息"
        className="grid grid-cols-1 sm:grid-cols-3 gap-5 mb-8"
      >
        {/* 教师信息卡 */}
        <article className="card-paper p-md">
          <p
            className="text-xs uppercase tracking-wider"
            style={{ color: "var(--color-ink-muted)" }}
          >
            班主任
          </p>
          <div className="flex items-center gap-md mt-sm">
            <span
              className="inline-flex w-12 h-12 items-center justify-center rounded-full font-serif text-lg"
              style={{
                background: "var(--color-accent-muted)",
                color: "var(--color-accent)",
              }}
              aria-hidden="true"
            >
              {cls.homeroomTeacher.slice(0, 1)}
            </span>
            <div>
              <p
                className="font-serif text-base"
                style={{ color: "var(--color-ink)" }}
              >
                {cls.homeroomTeacher}
              </p>
              <p
                className="text-xs"
                style={{ color: "var(--color-ink-muted)" }}
              >
                班级共 {cls.studentCount} 名学生
              </p>
            </div>
          </div>
        </article>

        {/* 学业信息卡 */}
        <article className="card-paper p-md">
          <p
            className="text-xs uppercase tracking-wider"
            style={{ color: "var(--color-ink-muted)" }}
          >
            学业信息
          </p>
          <dl className="mt-sm space-y-xs text-sm">
            <div className="flex items-baseline justify-between">
              <dt
                className="text-xs"
                style={{ color: "var(--color-ink-muted)" }}
              >
                年级
              </dt>
              <dd style={{ color: "var(--color-ink)" }}>{cls.grade}</dd>
            </div>
            <div className="flex items-baseline justify-between">
              <dt
                className="text-xs"
                style={{ color: "var(--color-ink-muted)" }}
              >
                学年
              </dt>
              <dd style={{ color: "var(--color-ink)" }}>{cls.year}</dd>
            </div>
            <div className="flex items-baseline justify-between">
              <dt
                className="text-xs"
                style={{ color: "var(--color-ink-muted)" }}
              >
                班级规模
              </dt>
              <dd style={{ color: "var(--color-ink)" }}>
                {cls.studentCount} 人
              </dd>
            </div>
          </dl>
        </article>

        {/* 教室信息卡 */}
        <article className="card-paper p-md">
          <p
            className="text-xs uppercase tracking-wider"
            style={{ color: "var(--color-ink-muted)" }}
          >
            教室信息
          </p>
          {classrooms.length === 0 ? (
            <p
              className="mt-sm text-sm"
              style={{ color: "var(--color-ink-subtle)" }}
            >
              暂无教室信息
            </p>
          ) : (
            <ul className="mt-sm space-y-xs">
              {classrooms.map((cr) => (
                <li
                  key={cr}
                  className="flex items-center gap-sm text-sm"
                  style={{ color: "var(--color-ink)" }}
                >
                  <span
                    className="inline-block w-1.5 h-1.5 rounded-full"
                    style={{ background: "var(--color-accent)" }}
                    aria-hidden="true"
                  />
                  {cr}
                </li>
              ))}
            </ul>
          )}
          {teachers.length > 0 ? (
            <p
              className="mt-sm text-xs"
              style={{ color: "var(--color-ink-subtle)" }}
            >
              任课教师：{teachers.join("、")}
            </p>
          ) : null}
        </article>
      </section>

      {/* 班级课表 */}
      <section aria-label="班级课表" className="card-paper p-md lg:p-lg">
        <div className="flex items-baseline justify-between mb-md">
          <h2
            className="text-lg font-serif"
            style={{ color: "var(--color-ink)" }}
          >
            班级课表
          </h2>
          <Link
            href="/schedule"
            className="text-xs hover:underline"
            style={{ color: "var(--color-accent)" }}
          >
            查看完整周课表 →
          </Link>
        </div>
        <div className="rule-thin mb-md" />

        {schedFetching ? (
          <p
            className="text-sm py-lg text-center"
            style={{ color: "var(--color-ink-muted)" }}
            aria-live="polite"
          >
            加载课表中…
          </p>
        ) : schedError ? (
          <div className="mark-left py-md px-md" aria-live="assertive">
            <p className="text-sm" style={{ color: "var(--color-ink)" }}>
              {schedError.message || "课表加载失败"}
            </p>
          </div>
        ) : scheduleItems.length === 0 ? (
          <p
            className="text-sm py-lg text-center"
            style={{ color: "var(--color-ink-muted)" }}
            role="status"
          >
            暂无课表数据
          </p>
        ) : (
          <WeeklyScheduleGrid grouped={grouped} />
        )}
      </section>
    </div>
  );
}

/** 周课表网格（5 列） */
function WeeklyScheduleGrid({
  grouped,
}: {
  grouped: Map<number, ScheduleItem[]>;
}): JSX.Element {
  return (
    <div
      className="hidden sm:grid grid-cols-5 gap-sm"
      role="grid"
      aria-label="周课表"
    >
      {WEEKDAYS.map((day) => {
        const dayItems = grouped.get(day) ?? [];
        return (
          <div key={day} role="row" className="flex flex-col">
            <div
              className="mb-sm pb-xs text-center border-b"
              style={{ borderColor: "var(--color-rule)" }}
            >
              <span
                className="font-serif text-sm"
                style={{ color: "var(--color-ink)" }}
              >
                {DAY_LABELS[day]}
              </span>
            </div>
            <div className="space-y-xs flex-1">
              {dayItems.map((item) => (
                <ScheduleCard key={item.id} item={item} />
              ))}
              {dayItems.length === 0 && (
                <p
                  className="text-xs py-md text-center"
                  style={{ color: "var(--color-ink-subtle)" }}
                >
                  无课
                </p>
              )}
            </div>
          </div>
        );
      })}
    </div>
  );
}

/** 单节课卡片 */
function ScheduleCard({ item }: { item: ScheduleItem }): JSX.Element {
  return (
    <div
      className="card-paper p-sm"
      role="gridcell"
      style={{ borderLeft: "2px solid var(--color-accent)" }}
    >
      <div className="flex items-baseline justify-between mb-xs">
        <span
          className="font-mono text-xs"
          style={{ color: "var(--color-ink-muted)" }}
        >
          {item.startTime}–{item.endTime}
        </span>
      </div>
      <p
        className="font-serif text-sm"
        style={{ color: "var(--color-ink)" }}
      >
        {item.subject}
      </p>
      <p
        className="text-xs mt-xs"
        style={{ color: "var(--color-ink-muted)" }}
      >
        {item.teacher} · {item.classroom}
      </p>
    </div>
  );
}
