"use client";

/**
 * Schedule — 我的课表（ai14，P5，路由 /schedule）
 *
 * 数据源：useMySchedule GraphQL hook
 * 视图：周课表网格（周一到周五，按时间段排列）
 * - 移动端：单日纵向列表，可切换日期
 * - 桌面端：5 列网格，每列一天
 *
 * 设计依据：纸感设计（card-paper + rule 分隔线）
 */

import { useState, useMemo } from "react";
import { 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];

/** 获取今日 dayOfWeek */
function getTodayDayOfWeek(): number {
  return new Date().getDay();
}

/** 按天分组 */
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);
  }
  // 每天按 startTime 排序
  for (const list of map.values()) {
    list.sort((a, b) => a.startTime.localeCompare(b.startTime));
  }
  return map;
}

export default function SchedulePage(): JSX.Element {
  const { data, fetching, error, reexecute } = useMySchedule();
  const items = data ?? [];
  const [selectedDay, setSelectedDay] = useState<number>(getTodayDayOfWeek());

  const grouped = useMemo(() => groupByDay(items), [items]);
  const todayLabel = DAY_LABELS[selectedDay] ?? "";

  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 ? (
        <p
          className="text-sm"
          style={{ color: "var(--color-ink-muted)" }}
          aria-live="polite"
        >
          加载中…
        </p>
      ) : error ? (
        <div className="mark-left py-md px-md mb-md" aria-live="assertive">
          <p
            className="text-sm"
            style={{ color: "var(--color-ink)" }}
          >
            {error.message || "加载失败"}
          </p>
          <button
            type="button"
            className="btn-secondary mt-sm"
            onClick={() => reexecute()}
          >
            重试
          </button>
        </div>
      ) : items.length === 0 ? (
        <p
          className="text-sm"
          style={{ color: "var(--color-ink-muted)" }}
          role="status"
        >
          暂无课表数据
        </p>
      ) : (
        <>
          {/* 移动端：日期切换 */}
          <div
            className="lg:hidden mb-md flex gap-xs overflow-x-auto"
            role="tablist"
            aria-label="选择日期"
          >
            {WEEKDAYS.map((day) => (
              <button
                key={day}
                type="button"
                role="tab"
                aria-selected={selectedDay === day}
                onClick={() => setSelectedDay(day)}
                className="px-md py-sm text-sm rounded whitespace-nowrap"
                style={{
                  background:
                    selectedDay === day
                      ? "var(--color-accent)"
                      : "transparent",
                  color:
                    selectedDay === day
                      ? "var(--color-paper)"
                      : "var(--color-ink)",
                  border: "1px solid var(--color-rule)",
                }}
              >
                {DAY_LABELS[day]}
              </button>
            ))}
          </div>

          {/* 移动端：单日列表 */}
          <div className="lg:hidden space-y-sm">
            {(grouped.get(selectedDay) ?? []).map((item) => (
              <ScheduleCard key={item.id} item={item} showDay={false} />
            ))}
            {(grouped.get(selectedDay) ?? []).length === 0 && (
              <p
                className="text-sm py-lg text-center"
                style={{ color: "var(--color-ink-muted)" }}
              >
                {todayLabel}无课
              </p>
            )}
          </div>

          {/* 桌面端：5 列网格 */}
          <div
            className="hidden lg:grid grid-cols-5 gap-md"
            role="grid"
            aria-label="周课表"
          >
            {WEEKDAYS.map((day) => {
              const dayItems = grouped.get(day) ?? [];
              const isToday = day === getTodayDayOfWeek();
              return (
                <div
                  key={day}
                  role="row"
                  className="flex flex-col"
                >
                  <div
                    className="mb-sm pb-xs text-center border-b"
                    style={{
                      borderColor: isToday
                        ? "var(--color-accent)"
                        : "var(--color-rule)",
                      borderBottomWidth: isToday ? "2px" : "1px",
                    }}
                  >
                    <span
                      className="font-serif text-sm"
                      style={{
                        color: isToday
                          ? "var(--color-accent)"
                          : "var(--color-ink)",
                      }}
                    >
                      {DAY_LABELS[day]}
                    </span>
                    {isToday && (
                      <span
                        className="ml-xs text-xs"
                        style={{ color: "var(--color-accent)" }}
                      >
                        ·今日
                      </span>
                    )}
                  </div>
                  <div className="space-y-sm flex-1">
                    {dayItems.map((item) => (
                      <ScheduleCard
                        key={item.id}
                        item={item}
                        showDay={false}
                      />
                    ))}
                    {dayItems.length === 0 && (
                      <p
                        className="text-xs py-md text-center"
                        style={{
                          color: "var(--color-ink-subtle)",
                        }}
                      >
                        无课
                      </p>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        </>
      )}
    </div>
  );
}

/** 单节课卡片 */
function ScheduleCard({
  item,
  showDay,
}: {
  item: ScheduleItem;
  showDay: boolean;
}): 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>
        {showDay && (
          <span
            className="text-xs"
            style={{ color: "var(--color-ink-subtle)" }}
          >
            {DAY_LABELS[item.dayOfWeek] ?? ""}
          </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>
  );
}
