"use client";

/**
 * 班级课表页 - 周课表网格
 *
 * 数据来源（P7 扩展，MSW mock）：
 * - GraphQL ClassScheduleQuery：按 classId 拉取周课表
 * - GraphQL ClassesQuery：班级下拉选项
 *
 * 布局：CSS Grid（周一到周五 × 8 节），每个卡片显示 学科/教师/教室
 *
 * 维护者：ai13（teacher-portal）
 */

import { useState, useMemo, Suspense } from "react";
import { useQuery } from "urql";
import { useSearchParams } from "next/navigation";
import Link from "next/link";
import { Loading, Empty } from "@edu/ui-components";
import { ClassesQuery } from "@/lib/graphql";
import type { Class } from "@/lib/graphql";
import { ClassScheduleQuery } from "@/lib/graphql-p7-admin";
import type { ClassScheduleItem } from "@/lib/graphql-p7-admin";

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

const DAYS = [1, 2, 3, 4, 5] as const;
const PERIODS = [1, 2, 3, 4, 5, 6, 7, 8] as const;

const PERIOD_TIMES: Record<number, { start: string; end: string }> = {
  1: { start: "08:00", end: "08:45" },
  2: { start: "08:55", end: "09:40" },
  3: { start: "10:00", end: "10:45" },
  4: { start: "10:55", end: "11:40" },
  5: { start: "13:30", end: "14:15" },
  6: { start: "14:25", end: "15:10" },
  7: { start: "15:25", end: "16:10" },
  8: { start: "16:20", end: "17:05" },
};

function ScheduleContent(): React.ReactNode {
  const searchParams = useSearchParams();
  const initialClassId = searchParams.get("classId") ?? "";

  const [classId, setClassId] = useState(initialClassId);

  const [classesResult] = useQuery({ query: ClassesQuery });
  const classes: Class[] = classesResult.data?.classes ?? [];
  const firstClassId = classes[0]?.id ?? "";
  const targetClassId = classId || firstClassId;

  const [scheduleResult] = useQuery({
    query: ClassScheduleQuery,
    variables: { classId: targetClassId },
    pause: !targetClassId,
  });

  const schedule: ClassScheduleItem[] =
    (scheduleResult.data?.classSchedule as ClassScheduleItem[] | undefined) ?? [];

  // 按 dayOfWeek + period 分组
  const grouped = useMemo(() => {
    const map: Record<string, ClassScheduleItem> = {};
    for (const item of schedule) {
      const key = `${item.dayOfWeek}-${item.period}`;
      map[key] = item;
    }
    return map;
  }, [schedule]);

  const currentClassName =
    classes.find((c) => c.id === targetClassId)?.name ?? "—";

  return (
    <div className="px-10 py-10">
      <header className="mb-8 flex items-baseline justify-between">
        <div>
          <p className="mb-2">
            <Link
              href="/classes"
              className="text-tiny uppercase tracking-wide text-ink-muted hover:opacity-70"
            >
              ← 返回班级列表
            </Link>
          </p>
          <h1 className="text-3xl font-serif text-ink">
            {currentClassName} - 课表
          </h1>
          <p className="mt-1 text-sm text-ink-muted">
            GraphQL ClassScheduleQuery · 周课表网格（P7 扩展，MSW mock）
          </p>
        </div>
      </header>

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

      {/* 班级筛选 */}
      <section className="mb-8">
        <div className="grid grid-cols-2 gap-6">
          <div>
            <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
              班级
            </label>
            <select
              value={targetClassId}
              onChange={(e) => setClassId(e.target.value)}
              className="w-full px-3 py-2 bg-transparent border-b border-rule text-sm font-sans text-ink focus:outline-none focus:border-accent"
            >
              <option value="">请选择班级</option>
              {classes.map((c) => (
                <option key={c.id} value={c.id}>
                  {c.name}
                </option>
              ))}
            </select>
          </div>
        </div>
      </section>

      {!targetClassId ? (
        <Empty title="请选择班级" description="选择后即可查看该班级的周课表" />
      ) : scheduleResult.fetching ? (
        <Loading lines={6} />
      ) : scheduleResult.error ? (
        <div className="mark-left mb-4 py-2 border-l-2 border-danger pl-md">
          <p className="text-sm px-3 text-danger">
            加载失败：{scheduleResult.error.message}
          </p>
        </div>
      ) : schedule.length === 0 ? (
        <Empty title="暂无课表" description="该班级尚未排课" />
      ) : (
        <section>
          <div className="flex items-baseline justify-between mb-4">
            <h2 className="text-xl font-serif text-ink">
              周课表
              <span className="ml-2 text-sm font-sans text-ink-muted">
                {schedule.length} 节
              </span>
            </h2>
            <p className="text-tiny text-ink-muted">
              周一至周五 · 共 {PERIODS.length} 节
            </p>
          </div>
          <div className="rule-thin mb-4" />

          {/* 课表网格：第一列为节次，后续 5 列为周一到周五 */}
          <div className="border border-rule rounded-card overflow-hidden">
            <div
              className="grid"
              style={{
                gridTemplateColumns: `80px repeat(${DAYS.length}, minmax(0, 1fr))`,
              }}
            >
              {/* 表头 */}
              <div className="px-3 py-2 text-tiny uppercase tracking-wide text-ink-muted bg-subtle border-b border-rule text-center">
                节次
              </div>
              {DAYS.map((day) => (
                <div
                  key={`head-${day}`}
                  className="px-3 py-2 text-tiny uppercase tracking-wide text-ink-muted bg-subtle border-b border-l border-rule text-center"
                >
                  {DAY_LABELS[day]}
                </div>
              ))}

              {/* 8 节 × 5 天 */}
              {PERIODS.map((period) => {
                const times = PERIOD_TIMES[period];
                return (
                  <div key={`row-${period}`} className="contents">
                    {/* 节次标签 */}
                    <div className="px-3 py-3 text-center border-t border-rule bg-subtle">
                      <p className="text-sm font-serif text-ink">{period}</p>
                      {times && (
                        <p className="mt-1 text-tiny font-mono text-ink-muted">
                          {times.start}
                        </p>
                      )}
                    </div>
                    {DAYS.map((day) => {
                      const key = `${day}-${period}`;
                      const item = grouped[key];
                      if (!item) {
                        return (
                          <div
                            key={`cell-${key}`}
                            className="px-3 py-3 border-t border-l border-rule text-tiny text-ink-muted"
                          >
                            —
                          </div>
                        );
                      }
                      const isSelfStudy = item.subject === "自习";
                      return (
                        <div
                          key={`cell-${key}`}
                          className={`px-3 py-3 border-t border-l border-rule ${
                            isSelfStudy ? "bg-subtle" : "bg-surface"
                          }`}
                        >
                          <p
                            className={`text-sm font-serif ${
                              isSelfStudy ? "text-ink-muted" : "text-ink"
                            }`}
                          >
                            {item.subject}
                          </p>
                          <p className="mt-1 text-tiny text-ink-muted">
                            {item.teacherName}
                          </p>
                          <p className="mt-0.5 text-tiny font-mono text-ink-muted">
                            {item.room}
                          </p>
                        </div>
                      );
                    })}
                  </div>
                );
              })}
            </div>
          </div>
        </section>
      )}
    </div>
  );
}

export default function ClassSchedulePage(): React.ReactNode {
  return (
    <Suspense
      fallback={
        <div className="px-10 py-10">
          <Loading lines={4} />
        </div>
      }
    >
      <ScheduleContent />
    </Suspense>
  );
}
