"use client";

/**
 * 教材列表 - 筛选 + 新建 + 表格 + 分页
 *
 * 数据来源（P7 扩展，MSW mock）：
 * - GraphQL TextbooksQuery：教材列表（q/subject/grade 筛选 + 分页 + 总数）
 * - GraphQL TextbookCreateMutation：新建教材
 *
 * 维护者：ai13（teacher-portal）
 */

import { useState, useMemo, useCallback } from "react";
import { useQuery, useMutation } from "urql";
import Link from "next/link";
import { Loading, Empty } from "@edu/ui-components";
import { TextbooksQuery, TextbookCreateMutation } from "@/lib/graphql-p7-exams";
import type {
  TextbookItem,
  TextbooksFilter,
  TextbookCreateInput,
} from "@/lib/graphql-p7-exams";
import {
  TEXTBOOK_SUBJECTS,
  TEXTBOOK_GRADES,
  TEXTBOOK_VERSIONS,
} from "@/mocks/fixtures/textbooks";

/** 新建教材弹窗的表单状态 */
interface TextbookFormState {
  title: string;
  subject: string;
  grade: string;
  version: string;
  coverUrl: string;
}

/** 初始空表单 */
function emptyForm(): TextbookFormState {
  return {
    title: "",
    subject: "",
    grade: "",
    version: "",
    coverUrl: "",
  };
}

export default function TextbooksPage(): React.ReactNode {
  // === 筛选条件 ===
  const [filterQ, setFilterQ] = useState("");
  const [filterSubject, setFilterSubject] = useState("all");
  const [filterGrade, setFilterGrade] = useState("all");
  const [page, setPage] = useState(1);
  const pageSize = 20;

  // === 新建弹窗状态 ===
  const [dialogOpen, setDialogOpen] = useState(false);
  const [form, setForm] = useState<TextbookFormState>(emptyForm());
  const [dialogError, setDialogError] = useState<string | null>(null);
  const [dialogSaving, setDialogSaving] = useState(false);

  // === GraphQL 查询 ===
  const filter: TextbooksFilter = useMemo(
    () => ({
      q: filterQ || null,
      subject: filterSubject === "all" ? null : filterSubject,
      grade: filterGrade === "all" ? null : filterGrade,
      page,
      pageSize,
    }),
    [filterQ, filterSubject, filterGrade, page],
  );

  const [result] = useQuery({
    query: TextbooksQuery,
    variables: { filter },
  });

  // === Mutations ===
  const [, createTextbook] = useMutation(TextbookCreateMutation);

  const items: TextbookItem[] =
    (result.data?.textbooks.items as TextbookItem[] | undefined) ?? [];
  const total = result.data?.textbooks.total ?? 0;
  const totalPages = Math.max(1, Math.ceil(total / pageSize));

  // === 操作 ===
  const openCreate = useCallback(() => {
    setForm(emptyForm());
    setDialogError(null);
    setDialogOpen(true);
  }, []);

  const submitForm = async () => {
    setDialogError(null);
    if (!form.title.trim()) {
      setDialogError("请填写教材名称");
      return;
    }
    if (!form.subject) {
      setDialogError("请选择学科");
      return;
    }
    if (!form.grade) {
      setDialogError("请选择年级");
      return;
    }
    if (!form.version) {
      setDialogError("请选择版本");
      return;
    }
    setDialogSaving(true);
    const input: TextbookCreateInput = {
      title: form.title.trim(),
      subject: form.subject,
      grade: form.grade,
      version: form.version,
      coverUrl: form.coverUrl.trim() || null,
    };
    const res = await createTextbook({ input });
    setDialogSaving(false);
    if (res.error) {
      setDialogError(res.error.message);
      return;
    }
    setDialogOpen(false);
  };

  const resetFilters = () => {
    setFilterQ("");
    setFilterSubject("all");
    setFilterGrade("all");
    setPage(1);
  };

  return (
    <div className="px-10 py-10">
      <header className="mb-8 flex items-baseline justify-between">
        <div>
          <h1 className="text-3xl font-serif text-ink">教材</h1>
          <p className="mt-1 text-sm text-ink-muted">
            GraphQL TextbooksQuery · content 域（P7 扩展，MSW mock）
          </p>
        </div>
        <button
          type="button"
          onClick={openCreate}
          className="px-4 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover"
        >
          新建教材
        </button>
      </header>

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

      {/* 筛选栏 */}
      <section className="mb-6">
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
          <input
            type="text"
            value={filterQ}
            onChange={(e) => {
              setFilterQ(e.target.value);
              setPage(1);
            }}
            placeholder="教材名称关键词"
            className="px-3 py-1.5 bg-transparent border border-rule rounded-button text-sm text-ink focus:outline-none"
          />
          <select
            value={filterSubject}
            onChange={(e) => {
              setFilterSubject(e.target.value);
              setPage(1);
            }}
            className="px-2 py-1.5 bg-transparent border border-rule rounded-button text-tiny text-ink focus:outline-none"
          >
            <option value="all">全部学科</option>
            {TEXTBOOK_SUBJECTS.map((s) => (
              <option key={s} value={s}>
                {s}
              </option>
            ))}
          </select>
          <select
            value={filterGrade}
            onChange={(e) => {
              setFilterGrade(e.target.value);
              setPage(1);
            }}
            className="px-2 py-1.5 bg-transparent border border-rule rounded-button text-tiny text-ink focus:outline-none"
          >
            <option value="all">全部年级</option>
            {TEXTBOOK_GRADES.map((g) => (
              <option key={g} value={g}>
                {g}
              </option>
            ))}
          </select>
          <button
            type="button"
            onClick={resetFilters}
            className="text-tiny uppercase tracking-wide text-ink-muted hover:opacity-70 text-left"
          >
            清空筛选
          </button>
        </div>
      </section>

      {/* 数据表 */}
      {result.fetching ? (
        <Loading lines={6} />
      ) : 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>
      ) : items.length === 0 ? (
        <Empty
          title="暂无教材"
          description="调整筛选条件或新建教材"
          action={
            <button
              type="button"
              onClick={openCreate}
              className="px-4 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover"
            >
              新建第一本教材
            </button>
          }
        />
      ) : (
        <div className="border border-rule rounded-card overflow-hidden">
          <table className="w-full text-sm">
            <thead className="bg-subtle">
              <tr className="border-b border-rule">
                <th className="text-left py-2 px-3 text-tiny uppercase tracking-wide text-ink-muted">
                  教材名
                </th>
                <th className="text-left py-2 px-3 text-tiny uppercase tracking-wide text-ink-muted">
                  学科
                </th>
                <th className="text-left py-2 px-3 text-tiny uppercase tracking-wide text-ink-muted">
                  年级
                </th>
                <th className="text-left py-2 px-3 text-tiny uppercase tracking-wide text-ink-muted">
                  版本
                </th>
                <th className="text-right py-2 px-3 text-tiny uppercase tracking-wide text-ink-muted">
                  章节数
                </th>
                <th className="text-right py-2 px-3 text-tiny uppercase tracking-wide text-ink-muted">
                  操作
                </th>
              </tr>
            </thead>
            <tbody>
              {items.map((tb) => (
                <tr
                  key={tb.id}
                  className="border-b border-rule hover:bg-subtle"
                >
                  <td className="py-2 px-3 text-ink">
                    {tb.title}
                  </td>
                  <td className="py-2 px-3 text-ink-muted">{tb.subject}</td>
                  <td className="py-2 px-3 text-ink-muted">{tb.grade}</td>
                  <td className="py-2 px-3 text-ink-muted">{tb.version}</td>
                  <td className="py-2 px-3 text-right font-mono text-ink">
                    {tb.chapterCount}
                  </td>
                  <td className="py-2 px-3 text-right">
                    <Link
                      href={`/textbooks/${tb.id}`}
                      className="text-tiny font-mono text-accent hover:opacity-70 mr-3"
                    >
                      阅读
                    </Link>
                    <button
                      type="button"
                      onClick={() =>
                        window.alert("教材编辑暂未实现（P7 mock）")
                      }
                      className="text-tiny font-mono text-ink-muted hover:opacity-70 mr-3"
                    >
                      编辑
                    </button>
                    <button
                      type="button"
                      onClick={() =>
                        window.alert("教材删除暂未实现（P7 mock）")
                      }
                      className="text-tiny font-mono text-danger hover:opacity-70"
                    >
                      删除
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* 分页 */}
      {total > 0 && (
        <div className="mt-4 flex items-center justify-between text-tiny text-ink-muted">
          <span>
            第 {page} / {totalPages} 页（共 {total} 本）
          </span>
          <div className="flex gap-2">
            <button
              type="button"
              onClick={() => setPage((p) => Math.max(1, p - 1))}
              disabled={page <= 1}
              className="px-3 py-1 border border-rule rounded-button disabled:opacity-30 hover:bg-subtle"
            >
              上一页
            </button>
            <button
              type="button"
              onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
              disabled={page >= totalPages}
              className="px-3 py-1 border border-rule rounded-button disabled:opacity-30 hover:bg-subtle"
            >
              下一页
            </button>
          </div>
        </div>
      )}

      {/* 新建教材弹窗 */}
      {dialogOpen && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-paper/80"
          onClick={() => !dialogSaving && setDialogOpen(false)}
        >
          <div
            className="bg-paper border border-rule rounded-card p-6 w-full max-w-lg mx-4 max-h-[90vh] overflow-y-auto"
            onClick={(e) => e.stopPropagation()}
          >
            <h2 className="text-xl font-serif text-ink mb-4">新建教材</h2>
            <div className="rule-thin mb-4" />
            <div className="space-y-4">
              {/* 教材名称 */}
              <div>
                <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
                  教材名称 <span className="text-danger">*</span>
                </label>
                <input
                  type="text"
                  value={form.title}
                  onChange={(e) =>
                    setForm((f) => ({ ...f, title: e.target.value }))
                  }
                  className="w-full px-3 py-2 bg-transparent border border-rule rounded-button text-sm text-ink focus:outline-none"
                  placeholder="如：高中数学必修一"
                />
              </div>
              {/* 学科 + 年级 */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
                    学科 <span className="text-danger">*</span>
                  </label>
                  <select
                    value={form.subject}
                    onChange={(e) =>
                      setForm((f) => ({ ...f, subject: e.target.value }))
                    }
                    className="w-full px-3 py-2 bg-transparent border border-rule rounded-button text-sm text-ink focus:outline-none"
                  >
                    <option value="">请选择</option>
                    {TEXTBOOK_SUBJECTS.map((s) => (
                      <option key={s} value={s}>
                        {s}
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
                    年级 <span className="text-danger">*</span>
                  </label>
                  <select
                    value={form.grade}
                    onChange={(e) =>
                      setForm((f) => ({ ...f, grade: e.target.value }))
                    }
                    className="w-full px-3 py-2 bg-transparent border border-rule rounded-button text-sm text-ink focus:outline-none"
                  >
                    <option value="">请选择</option>
                    {TEXTBOOK_GRADES.map((g) => (
                      <option key={g} value={g}>
                        {g}
                      </option>
                    ))}
                  </select>
                </div>
              </div>
              {/* 版本 + 封面 */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
                    版本 <span className="text-danger">*</span>
                  </label>
                  <select
                    value={form.version}
                    onChange={(e) =>
                      setForm((f) => ({ ...f, version: e.target.value }))
                    }
                    className="w-full px-3 py-2 bg-transparent border border-rule rounded-button text-sm text-ink focus:outline-none"
                  >
                    <option value="">请选择</option>
                    {TEXTBOOK_VERSIONS.map((v) => (
                      <option key={v} value={v}>
                        {v}
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
                    封面 URL
                  </label>
                  <input
                    type="text"
                    value={form.coverUrl}
                    onChange={(e) =>
                      setForm((f) => ({ ...f, coverUrl: e.target.value }))
                    }
                    className="w-full px-3 py-2 bg-transparent border border-rule rounded-button text-sm text-ink focus:outline-none"
                    placeholder="可选"
                  />
                </div>
              </div>
              {/* 错误提示 */}
              {dialogError && (
                <div className="mark-left py-2 border-l-2 border-danger pl-md">
                  <p className="text-sm px-3 text-danger">{dialogError}</p>
                </div>
              )}
              {/* 操作按钮 */}
              <div className="flex items-center gap-3 pt-2">
                <button
                  type="button"
                  onClick={submitForm}
                  disabled={dialogSaving}
                  className="px-4 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover disabled:opacity-50"
                >
                  {dialogSaving ? "保存中..." : "创建教材"}
                </button>
                <button
                  type="button"
                  onClick={() => setDialogOpen(false)}
                  disabled={dialogSaving}
                  className="text-tiny uppercase tracking-wide text-ink-muted hover:opacity-70"
                >
                  取消
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      <p className="mt-8 text-tiny text-ink-muted">
        <Link
          href="/dashboard"
          className="text-tiny uppercase tracking-wide text-ink-muted hover:opacity-70"
        >
          ← 返回仪表盘
        </Link>
      </p>
    </div>
  );
}
