"use client";

/**
 * 校内课案库（P7-insights）
 *
 * 数据来源：GraphQL LessonPlanLibraryQuery + ForkLessonPlanMutation
 *
 * 功能：
 * - 学科 + 年级筛选
 * - 列表：标题/作者/学科/年级/章节/评分/Fork 数/操作
 * - "Fork 到我的课案" 调用 ForkLessonPlanMutation
 *
 * 维护者：ai13（teacher-portal）
 */

import { useState } from "react";
import { useQuery, useMutation } from "urql";
import Link from "next/link";
import { Loading, Empty } from "@edu/ui-components";
import {
  LessonPlanLibraryQuery,
  ForkLessonPlanMutation,
} from "@/lib/graphql-p7-insights";
import type { LessonPlanLibraryItem } from "@/lib/graphql-p7-insights";

const SUBJECT_FILTERS = ["全部", "语文", "数学", "英语"] as const;
const GRADE_FILTERS = [
  "全部",
  "小学三年级",
  "小学六年级",
  "初中一年级",
  "高中一年级",
  "高中三年级",
] as const;

export default function LessonPlanLibraryPage(): JSX.Element {
  const [subject, setSubject] = useState<string>("全部");
  const [grade, setGrade] = useState<string>("全部");
  const [forkingId, setForkingId] = useState<string | null>(null);
  const [forkedIds, setForkedIds] = useState<Set<string>>(new Set());
  const [error, setError] = useState<string | null>(null);

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

  const [, forkLessonPlan] = useMutation(ForkLessonPlanMutation);

  const items: LessonPlanLibraryItem[] = result.data?.lessonPlanLibrary ?? [];

  const handleFork = async (planId: string): Promise<void> => {
    setForkingId(planId);
    setError(null);
    const res = await forkLessonPlan({ planId });
    setForkingId(null);
    if (res.error || !res.data?.forkLessonPlan) {
      setError(res.error?.message ?? "Fork 失败");
      return;
    }
    setForkedIds((prev) => {
      const next = new Set(prev);
      next.add(planId);
      return next;
    });
  };

  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 LessonPlanLibraryQuery · 浏览校内同仁分享的课案并 Fork（P7-insights）
        </p>
      </header>

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

      {/* 筛选 */}
      <div className="mb-6 flex items-baseline gap-6 flex-wrap">
        <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 items-center gap-3">
          <label className="text-tiny uppercase tracking-wide text-ink-muted">
            年级
          </label>
          <select
            value={grade}
            onChange={(e) => setGrade(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"
          >
            {GRADE_FILTERS.map((g) => (
              <option key={g} value={g}>
                {g}
              </option>
            ))}
          </select>
        </div>
      </div>

      {error && (
        <div className="mark-left mb-4 py-2 border-l-2 border-danger pl-md">
          <p className="text-sm px-3 text-danger">{error}</p>
        </div>
      )}

      {result.fetching ? (
        <Loading lines={5} />
      ) : items.length === 0 ? (
        <Empty
          title="暂无课案"
          description="当前筛选条件下没有可 Fork 的校内课案"
        />
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {items.map((item) => {
            const forked = forkedIds.has(item.id);
            const forking = forkingId === item.id;
            return (
              <article
                key={item.id}
                className="p-5 border border-rule rounded-card bg-surface flex flex-col gap-3"
              >
                <h3 className="font-serif text-lg text-ink">{item.title}</h3>
                <div className="flex flex-wrap gap-1.5">
                  <span className="px-2 py-0.5 rounded bg-subtle text-tiny text-ink">
                    {item.subject}
                  </span>
                  <span className="px-2 py-0.5 rounded bg-subtle text-tiny text-ink">
                    {item.grade}
                  </span>
                  <span className="px-2 py-0.5 rounded bg-subtle text-tiny text-ink-muted">
                    {item.chapter}
                  </span>
                </div>
                <p className="text-tiny text-ink-muted">
                  作者：{item.author} · Fork 数 {item.forkCount} · 评分{" "}
                  <span className="font-mono text-accent">{item.rating}</span>
                </p>
                <button
                  type="button"
                  onClick={() => handleFork(item.id)}
                  disabled={forking || forked}
                  className="mt-2 px-3 py-1.5 text-tiny text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {forking
                    ? "Fork 中…"
                    : forked
                      ? "已 Fork ✓"
                      : "Fork 到我的课案"}
                </button>
              </article>
            );
          })}
        </div>
      )}
    </div>
  );
}
