"use client";

/**
 * 创建选修课表单页
 *
 * 数据来源（P7 扩展，MSW mock）：
 * - GraphQL CreateElectiveCourseMutation：创建选修课（草稿/发布）
 *
 * 布局：
 * - 表单字段：课程名/学科 select/年级 select/容量 input/学期 select/描述 textarea
 * - "保存草稿"/"发布" 按钮
 *
 * 维护者：ai13（teacher-portal）
 */

import { useState } from "react";
import { useMutation } from "urql";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { CreateElectiveCourseMutation } from "@/lib/graphql-p7-advanced";

/** 学科选项 */
const SUBJECT_OPTIONS = [
  "数学", "语文", "英语", "物理", "化学", "生物",
  "历史", "地理", "信息技术", "美术",
];

/** 年级选项 */
const GRADE_OPTIONS = ["高一", "高二", "高三"];

/** 学期选项 */
const SEMESTER_OPTIONS = ["2026春季", "2025秋季", "2026秋季"];

export default function CreateElectivePage(): React.ReactNode {
  const router = useRouter();

  const [createResult, createCourse] = useMutation(CreateElectiveCourseMutation);

  const [title, setTitle] = useState("");
  const [subject, setSubject] = useState(SUBJECT_OPTIONS[0] ?? "数学");
  const [grade, setGrade] = useState(GRADE_OPTIONS[0] ?? "高一");
  const [capacity, setCapacity] = useState("40");
  const [semester, setSemester] = useState(SEMESTER_OPTIONS[0] ?? "2026春季");
  const [description, setDescription] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);

  /** 提交创建（publish=true 发布，false 保存草稿） */
  const handleSubmit = async (publish: boolean) => {
    setError(null);

    if (!title.trim()) {
      setError("请填写课程名");
      return;
    }

    setSubmitting(true);
    const res = await createCourse({
      input: {
        title: title.trim(),
        subject,
        grade,
        capacity: Number(capacity) || 0,
        semester,
        description: description.trim() || null,
      },
    });
    setSubmitting(false);

    if (res.error) {
      setError(res.error.message);
      return;
    }

    // 成功后跳回列表（publish 标记仅用于 UI 提示，mock 不区分）
    if (publish) {
      // 发布：mock 中通过 PublishElectiveCourseMutation 调用，此处简化为创建后跳转
    }
    router.push("/elective");
  };

  return (
    <div className="px-10 py-10">
      <header className="mb-8">
        <p className="mb-2">
          <Link
            href="/elective"
            className="text-tiny uppercase tracking-wide text-ink-muted hover:opacity-70"
          >
            ← 返回选修课列表
          </Link>
        </p>
        <h1 className="text-3xl font-serif text-ink">创建选修课</h1>
        <p className="mt-1 text-sm text-ink-muted">
          GraphQL CreateElectiveCourseMutation · core-edu 域（P7 扩展，MSW mock）
        </p>
      </header>

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

      <section className="max-w-2xl">
        <form className="space-y-6">
          {/* 课程名 */}
          <div>
            <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
              课程名 <span className="text-danger">*</span>
            </label>
            <input
              type="text"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              className="w-full px-3 py-2 bg-transparent border-b border-rule text-sm text-ink focus:outline-none focus:border-b-2"
              placeholder="例如：趣味数学建模"
              required
            />
          </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={subject}
                onChange={(e) => setSubject(e.target.value)}
                className="w-full px-3 py-2 bg-transparent border border-rule rounded-button text-sm text-ink focus:outline-none"
              >
                {SUBJECT_OPTIONS.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={grade}
                onChange={(e) => setGrade(e.target.value)}
                className="w-full px-3 py-2 bg-transparent border border-rule rounded-button text-sm text-ink focus:outline-none"
              >
                {GRADE_OPTIONS.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>
              <input
                type="number"
                min={1}
                value={capacity}
                onChange={(e) => setCapacity(e.target.value)}
                className="w-full px-3 py-2 bg-transparent border-b border-rule text-sm text-ink focus:outline-none focus:border-b-2"
                required
              />
            </div>
            <div>
              <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
                学期 <span className="text-danger">*</span>
              </label>
              <select
                value={semester}
                onChange={(e) => setSemester(e.target.value)}
                className="w-full px-3 py-2 bg-transparent border border-rule rounded-button text-sm text-ink focus:outline-none"
              >
                {SEMESTER_OPTIONS.map((s) => (
                  <option key={s} value={s}>
                    {s}
                  </option>
                ))}
              </select>
            </div>
          </div>

          {/* 描述 */}
          <div>
            <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
              描述
            </label>
            <textarea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              rows={3}
              className="w-full px-3 py-2 bg-transparent border border-rule rounded-button text-sm text-ink focus:outline-none"
              placeholder="课程简介、选课要求等"
            />
          </div>

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

          {/* 操作按钮 */}
          <div className="flex items-center gap-4 pt-4">
            <button
              type="button"
              onClick={() => handleSubmit(false)}
              disabled={submitting}
              className="px-4 py-2 text-sm text-ink bg-transparent border border-rule rounded-button hover:bg-subtle disabled:opacity-50"
            >
              {submitting ? "提交中..." : "保存草稿"}
            </button>
            <button
              type="button"
              onClick={() => handleSubmit(true)}
              disabled={submitting}
              className="px-4 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover disabled:opacity-50"
            >
              {submitting ? "提交中..." : "发布"}
            </button>
            <Link
              href="/elective"
              className="text-tiny uppercase tracking-wide text-ink-muted hover:opacity-70"
            >
              取消
            </Link>
            {createResult.data && (
              <span className="text-tiny text-success">创建成功</span>
            )}
          </div>
        </form>
      </section>
    </div>
  );
}
