"use client";

/**
 * 课案列表页（P7-insights）
 *
 * 数据来源（02-architecture-design.md §6 备课）：
 * - GraphQL LessonPlansQuery
 *
 * 功能：
 * - 学科筛选
 * - 列表：标题/学科/年级/章节/状态/更新时间/操作
 * - "新建课案" 链接（→ /lesson-plans/new）
 * - "校库" 链接（→ /lesson-plans/library）
 * - "日历视图" 链接（→ /lesson-plans/calendar）
 *
 * 维护者：ai13（teacher-portal）
 */

import { useState } from "react";
import { useQuery } from "urql";
import Link from "next/link";
import { Loading, Empty } from "@edu/ui-components";
import { LessonPlansQuery } from "@/lib/graphql-p7-insights";
import type { LessonPlanItem, LessonPlanStatus } from "@/lib/graphql-p7-insights";

const SUBJECT_FILTERS = ["全部", "语文", "数学", "英语"] as const;

const STATUS_LABEL: Record<LessonPlanStatus, string> = {
  DRAFT: "草稿",
  PUBLISHED: "已发布",
  ARCHIVED: "已归档",
};

function formatDate(iso: string): string {
  return iso.slice(0, 16).replace("T", " ");
}

export default function LessonPlansPage(): JSX.Element {
  const [subject, setSubject] = useState<string>("全部");

  const [result] = useQuery({
    query: LessonPlansQuery,
    variables: subject === "全部" ? {} : { subject },
  });

  const plans: LessonPlanItem[] = result.data?.lessonPlans ?? [];

  return (
    <div className="px-10 py-10">
      <header className="mb-8">
        <h1 className="text-3xl font-serif text-ink">课案管理</h1>
        <p className="mt-1 text-sm text-ink-muted">
          GraphQL LessonPlansQuery · 课案列表与编辑入口（P7-insights，MSW mock）
        </p>
      </header>

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

      {/* 工具栏 */}
      <div className="mb-6 flex items-baseline justify-between flex-wrap gap-4">
        <div className="flex items-center gap-3">
          <label className="text-tiny uppercase tracking-wide text-ink-muted">
            学科
          </label>
          <select
            value={subject}
            onChange={(e) => setSubject(e.target.value)}
            className="px-3 py-2 bg-transparent border-b border-rule text-sm font-sans text-ink focus:outline-none focus:border-accent"
          >
            {SUBJECT_FILTERS.map((s) => (
              <option key={s} value={s}>
                {s}
              </option>
            ))}
          </select>
        </div>
        <div className="flex gap-3">
          <Link
            href="/lesson-plans/new"
            className="px-4 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover"
          >
            新建课案
          </Link>
          <Link
            href="/lesson-plans/library"
            className="px-4 py-2 text-sm text-ink border border-rule rounded-button hover:bg-subtle"
          >
            校库
          </Link>
          <Link
            href="/lesson-plans/calendar"
            className="px-4 py-2 text-sm text-ink border border-rule rounded-button hover:bg-subtle"
          >
            日历视图
          </Link>
        </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>
      ) : plans.length === 0 ? (
        <Empty
          title="暂无课案"
          description="点击右上角「新建课案」开始创建第一份课案"
        />
      ) : (
        <table className="w-full text-sm">
          <thead>
            <tr className="text-left text-tiny uppercase tracking-wide text-ink-muted border-b border-rule">
              <th className="py-3 pr-4 font-normal">标题</th>
              <th className="py-3 pr-4 font-normal">学科</th>
              <th className="py-3 pr-4 font-normal">年级</th>
              <th className="py-3 pr-4 font-normal">章节</th>
              <th className="py-3 pr-4 font-normal">状态</th>
              <th className="py-3 pr-4 font-normal">更新时间</th>
              <th className="py-3 pr-4 font-normal text-right">操作</th>
            </tr>
          </thead>
          <tbody>
            {plans.map((p) => (
              <tr key={p.id} className="border-b border-rule">
                <td className="py-3 pr-4">
                  <Link
                    href={`/lesson-plans/${p.id}/edit`}
                    className="font-serif text-ink hover:text-accent"
                  >
                    {p.title}
                  </Link>
                </td>
                <td className="py-3 pr-4 text-ink">{p.subject}</td>
                <td className="py-3 pr-4 text-ink">{p.grade}</td>
                <td className="py-3 pr-4 text-ink-muted">{p.chapter}</td>
                <td className="py-3 pr-4">
                  <span className="px-2 py-0.5 rounded bg-subtle text-tiny text-ink">
                    {STATUS_LABEL[p.status]}
                  </span>
                </td>
                <td className="py-3 pr-4 text-ink-muted font-mono text-tiny">
                  {formatDate(p.updatedAt)}
                </td>
                <td className="py-3 pr-4 text-right">
                  <Link
                    href={`/lesson-plans/${p.id}/edit`}
                    className="text-tiny uppercase tracking-wide text-accent hover:opacity-70"
                  >
                    编辑
                  </Link>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      )}
    </div>
  );
}
