// 备课列表页面（家长查看子女备课，只读，含学科筛选）
// 依据：02-architecture-design.md §3.1 路由结构
// 路由：/parent/lesson-plans

"use client";

import { useQueryState, parseAsString } from "nuqs";
import { useChildLessonPlans } from "@/hooks/useChildLessonPlans";
import { useChildSwitcher } from "@/hooks/useChildSwitcher";
import { LessonPlanList } from "@/components/LessonPlanList";

export default function LessonPlansPage(): JSX.Element {
  const { currentChild } = useChildSwitcher();
  const [subject, setSubject] = useQueryState(
    "subject",
    parseAsString.withDefault(""),
  );
  const { lessonPlans, loading, error } = useChildLessonPlans(
    subject || undefined,
  );

  // 只显示已发布备课（display rule，防御性过滤）
  const publishedPlans = lessonPlans.filter((p) => p.status === "published");
  // 学科选项来自已发布备课
  const subjects = Array.from(new Set(publishedPlans.map((p) => p.subject)));
  // 学科筛选（nuqs + 客户端兜底，兼容 mock 不按 subject 过滤）
  const visiblePlans = subject
    ? publishedPlans.filter((p) => p.subject === subject)
    : publishedPlans;

  if (loading) {
    return (
      <div className="space-y-4" role="status" aria-live="polite">
        <span className="skeleton h-8 w-48 rounded" aria-hidden="true" />
        <span className="skeleton h-10 w-full rounded" aria-hidden="true" />
        <span className="skeleton h-40 w-full rounded" aria-hidden="true" />
        <span className="skeleton h-40 w-full rounded" aria-hidden="true" />
        <span className="sr-only">加载备课列表中...</span>
      </div>
    );
  }

  if (error) {
    return (
      <div
        role="alert"
        className="rounded border border-danger p-4 text-sm text-danger"
      >
        加载失败：{error.message}
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <h1 className="font-serif text-2xl">{currentChild?.name}的备课</h1>

      {/* 学科筛选 */}
      <div className="space-y-1">
        <label htmlFor="lesson-subject" className="text-xs text-ink-muted">
          学科筛选
        </label>
        <select
          id="lesson-subject"
          value={subject}
          onChange={(e) => setSubject(e.target.value || null)}
          className="rounded border border-rule bg-paper px-3 py-2 text-sm focus:outline-none"
        >
          <option value="">全部学科</option>
          {subjects.map((s) => (
            <option key={s} value={s}>
              {s}
            </option>
          ))}
        </select>
      </div>

      <LessonPlanList lessonPlans={visiblePlans} />
    </div>
  );
}
