"use client";

/**
 * 课案日历视图（P7-insights）
 *
 * 数据来源：GraphQL LessonPlanCalendarQuery
 *
 * 功能：
 * - 月份切换
 * - 日历网格（每天显示课案数，点击展开当天课案列表）
 * - CSS Grid 实现
 *
 * 维护者：ai13（teacher-portal）
 */

import { useState, useMemo } from "react";
import { useQuery } from "urql";
import Link from "next/link";
import { Loading } from "@edu/ui-components";
import { LessonPlanCalendarQuery } from "@/lib/graphql-p7-insights";
import type { LessonPlanCalendarDay } from "@/lib/graphql-p7-insights";

const WEEKDAYS = ["一", "二", "三", "四", "五", "六", "日"];

export default function LessonPlanCalendarPage(): JSX.Element {
  const today = new Date();
  const [year, setYear] = useState<number>(today.getFullYear());
  const [month, setMonth] = useState<number>(today.getMonth() + 1);
  const [selectedDay, setSelectedDay] = useState<LessonPlanCalendarDay | null>(
    null,
  );

  const [result] = useQuery({
    query: LessonPlanCalendarQuery,
    variables: { year, month },
  });

  const calendar = result.data?.lessonPlanCalendar;

  /** 月首日 weekday（周一为 0） */
  const firstWeekday = useMemo(() => {
    const first = new Date(year, month - 1, 1);
    // JS getDay：周日=0，周一=1...；我们以周一为起始，转换
    return (first.getDay() + 6) % 7;
  }, [year, month]);

  /** 月份天数 */
  const daysInMonth = useMemo(
    () => new Date(year, month, 0).getDate(),
    [year, month],
  );

  const goPrevMonth = (): void => {
    if (month === 1) {
      setYear((y) => y - 1);
      setMonth(12);
    } else {
      setMonth((m) => m - 1);
    }
    setSelectedDay(null);
  };

  const goNextMonth = (): void => {
    if (month === 12) {
      setYear((y) => y + 1);
      setMonth(1);
    } else {
      setMonth((m) => m + 1);
    }
    setSelectedDay(null);
  };

  /** 按日期生成单元格（含前置空格） */
  const cells: Array<{ day: number; data: LessonPlanCalendarDay | null }> = useMemo(() => {
    const list: Array<{ day: number; data: LessonPlanCalendarDay | null }> = [];
    for (let i = 0; i < firstWeekday; i++) {
      list.push({ day: 0, data: null });
    }
    const dayMap = new Map<string, LessonPlanCalendarDay>();
    calendar?.days.forEach((d: LessonPlanCalendarDay) => dayMap.set(d.date, d));
    for (let d = 1; d <= daysInMonth; d++) {
      const dateStr = `${year}-${String(month).padStart(2, "0")}-${String(d).padStart(2, "0")}`;
      list.push({ day: d, data: dayMap.get(dateStr) ?? null });
    }
    return list;
  }, [firstWeekday, daysInMonth, calendar, year, month]);

  return (
    <div className="px-10 py-10">
      <header className="mb-8">
        <Link
          href="/lesson-plans"
          className="text-tiny uppercase tracking-wide text-ink-muted hover:opacity-70"
        >
          ← 返回课案列表
        </Link>
        <h1 className="mt-3 text-3xl font-serif text-ink">课案日历</h1>
        <p className="mt-1 text-sm text-ink-muted">
          GraphQL LessonPlanCalendarQuery · 按月份浏览每日课案分布（P7-insights）
        </p>
      </header>

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

      {/* 月份切换 */}
      <div className="mb-6 flex items-center justify-between">
        <h2 className="text-xl font-serif text-ink">
          {year} 年 {month} 月
        </h2>
        <div className="flex gap-2">
          <button
            type="button"
            onClick={goPrevMonth}
            className="px-3 py-1.5 text-sm text-ink border border-rule rounded-button hover:bg-subtle"
          >
            ← 上月
          </button>
          <button
            type="button"
            onClick={goNextMonth}
            className="px-3 py-1.5 text-sm text-ink border border-rule rounded-button hover:bg-subtle"
          >
            下月 →
          </button>
        </div>
      </div>

      {result.fetching ? (
        <Loading lines={5} />
      ) : result.error ? (
        <div className="mark-left mb-4 py-2 border-l-2 border-danger pl-md">
          <p className="text-sm px-3 text-danger">
            加载失败：{result.error.message}
          </p>
        </div>
      ) : (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* 日历网格 */}
          <div className="lg:col-span-2">
            <div className="grid grid-cols-7 gap-1 mb-2">
              {WEEKDAYS.map((w) => (
                <div
                  key={w}
                  className="text-center text-tiny uppercase tracking-wide text-ink-muted py-2"
                >
                  {w}
                </div>
              ))}
            </div>
            <div className="grid grid-cols-7 gap-1">
              {cells.map((c, i) => {
                if (c.day === 0) {
                  return <div key={`empty-${i}`} className="aspect-square" />;
                }
                const data = c.data;
                const count = data?.planCount ?? 0;
                const isSelected =
                  selectedDay?.date === (data?.date ?? "");
                return (
                  <button
                    key={`day-${c.day}`}
                    type="button"
                    onClick={() => setSelectedDay(data)}
                    className={`aspect-square p-2 border rounded text-left transition-colors ${
                      isSelected
                        ? "border-accent bg-accent/10"
                        : count > 0
                          ? "border-rule bg-surface hover:bg-subtle"
                          : "border-rule bg-transparent hover:bg-subtle"
                    }`}
                  >
                    <div className="text-sm font-serif text-ink">{c.day}</div>
                    {count > 0 && (
                      <div className="mt-1 text-tiny font-mono text-accent">
                        {count} 课案
                      </div>
                    )}
                  </button>
                );
              })}
            </div>
          </div>

          {/* 当天课案列表 */}
          <aside className="p-5 border border-rule rounded-card bg-surface">
            <h3 className="text-tiny uppercase tracking-wide text-ink-muted mb-3">
              当天课案
            </h3>
            {!selectedDay || selectedDay.planCount === 0 ? (
              <p className="text-sm text-ink-muted">
                {selectedDay
                  ? `${selectedDay.date} 当天无课案`
                  : "点击日历选择某一天查看课案列表"}
              </p>
            ) : (
              <>
                <p className="text-sm text-ink mb-3 font-serif">
                  {selectedDay.date}
                </p>
                <ul className="space-y-2">
                  {selectedDay.planTitles.map((t, i) => (
                    <li
                      key={i}
                      className="text-sm text-ink py-2 border-b border-rule"
                    >
                      {t}
                    </li>
                  ))}
                </ul>
              </>
            )}
          </aside>
        </div>
      )}
    </div>
  );
}
