"use client";

/**
 * 新建课案页（P7-insights）
 *
 * 数据来源：GraphQL CreateLessonPlanMutation
 *
 * 功能：
 * - 模板选择器（5 个模板）
 * - 表单：标题/学科/年级/章节/教材关联
 * - "选择模板后创建" 跳转到 /lesson-plans/[planId]/edit
 *
 * 维护者：ai13（teacher-portal）
 */

import { useState } from "react";
import { useMutation } from "urql";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Loading } from "@edu/ui-components";
import { CreateLessonPlanMutation } from "@/lib/graphql-p7-insights";
import type {
  CreateLessonPlanInput,
  LessonPlanTemplate,
} from "@/lib/graphql-p7-insights";
import { LESSON_PLAN_TEMPLATES } from "@/mocks/fixtures/lesson-plans";

const SUBJECTS = ["语文", "数学", "英语"] as const;
const GRADES = [
  "小学三年级",
  "小学六年级",
  "初中一年级",
  "高中一年级",
  "高中三年级",
] as const;

export default function NewLessonPlanPage(): JSX.Element {
  const router = useRouter();
  const [template, setTemplate] = useState<LessonPlanTemplate>("REGULAR");
  const [title, setTitle] = useState("");
  const [subject, setSubject] = useState<string>(SUBJECTS[0] ?? "数学");
  const [grade, setGrade] = useState<string>(GRADES[0] ?? "小学三年级");
  const [chapter, setChapter] = useState("");
  const [textbookId, setTextbookId] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [, createLessonPlan] = useMutation(CreateLessonPlanMutation);

  const handleCreate = async (): Promise<void> => {
    if (!title || !chapter) {
      setError("请填写标题与章节");
      return;
    }
    setSubmitting(true);
    setError(null);
    const input: CreateLessonPlanInput = {
      title,
      subject,
      grade,
      chapter,
      textbookId: textbookId || null,
      template,
    };
    const res = await createLessonPlan({ input });
    setSubmitting(false);
    if (res.error || !res.data?.createLessonPlan) {
      setError(res.error?.message ?? "创建失败");
      return;
    }
    const created = res.data.createLessonPlan as { id: string };
    router.push(`/lesson-plans/${created.id}/edit`);
  };

  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 CreateLessonPlanMutation · 选择模板后创建跳转至编辑器（P7-insights）
        </p>
      </header>

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

      {/* 模板选择器 */}
      <section className="mb-10">
        <h2 className="text-xl font-serif text-ink mb-4">选择模板</h2>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {LESSON_PLAN_TEMPLATES.map((t) => {
            const active = t.id === template;
            return (
              <button
                key={t.id}
                type="button"
                onClick={() => setTemplate(t.id)}
                className={`p-4 border rounded-card text-left transition-colors ${
                  active
                    ? "border-accent bg-accent/10"
                    : "border-rule bg-surface hover:bg-subtle"
                }`}
              >
                <p className="font-serif text-ink">{t.name}</p>
                <p className="mt-1 text-tiny text-ink-muted">{t.description}</p>
              </button>
            );
          })}
        </div>
      </section>

      {/* 表单 */}
      <section className="mb-8 max-w-2xl">
        <h2 className="text-xl font-serif text-ink mb-4">基本信息</h2>
        {submitting ? (
          <Loading lines={4} />
        ) : (
          <div className="grid grid-cols-2 gap-4">
            <label className="col-span-2 flex flex-col gap-1">
              <span className="text-tiny uppercase tracking-wide text-ink-muted">
                标题
              </span>
              <input
                type="text"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                placeholder="如：函数的单调性与极值"
                className="px-3 py-2 bg-transparent border-b border-rule text-sm text-ink focus:outline-none focus:border-accent"
              />
            </label>
            <label className="flex flex-col gap-1">
              <span className="text-tiny uppercase tracking-wide text-ink-muted">
                学科
              </span>
              <select
                value={subject}
                onChange={(e) => setSubject(e.target.value)}
                className="px-3 py-2 bg-transparent border-b border-rule text-sm text-ink"
              >
                {SUBJECTS.map((s) => (
                  <option key={s} value={s}>
                    {s}
                  </option>
                ))}
              </select>
            </label>
            <label className="flex flex-col gap-1">
              <span className="text-tiny uppercase tracking-wide text-ink-muted">
                年级
              </span>
              <select
                value={grade}
                onChange={(e) => setGrade(e.target.value)}
                className="px-3 py-2 bg-transparent border-b border-rule text-sm text-ink"
              >
                {GRADES.map((g) => (
                  <option key={g} value={g}>
                    {g}
                  </option>
                ))}
              </select>
            </label>
            <label className="col-span-2 flex flex-col gap-1">
              <span className="text-tiny uppercase tracking-wide text-ink-muted">
                章节
              </span>
              <input
                type="text"
                value={chapter}
                onChange={(e) => setChapter(e.target.value)}
                placeholder="如：选修 2-2·导数应用"
                className="px-3 py-2 bg-transparent border-b border-rule text-sm text-ink focus:outline-none focus:border-accent"
              />
            </label>
            <label className="col-span-2 flex flex-col gap-1">
              <span className="text-tiny uppercase tracking-wide text-ink-muted">
                教材关联（可选）
              </span>
              <input
                type="text"
                value={textbookId}
                onChange={(e) => setTextbookId(e.target.value)}
                placeholder="如：tb-001"
                className="px-3 py-2 bg-transparent border-b border-rule text-sm text-ink focus:outline-none focus:border-accent"
              />
            </label>
          </div>
        )}

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

        <div className="mt-6 flex gap-3">
          <button
            type="button"
            onClick={handleCreate}
            disabled={submitting}
            className="px-5 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover disabled:opacity-50"
          >
            {submitting ? "创建中…" : "选择模板后创建"}
          </button>
          <Link
            href="/lesson-plans"
            className="px-5 py-2 text-sm text-ink border border-rule rounded-button hover:bg-subtle"
          >
            取消
          </Link>
        </div>
      </section>
    </div>
  );
}
