"use client";

/**
 * 新建考试表单页
 *
 * 数据来源（contract.md §2.4）：GraphQL CreateExamMutation（P3 扩展，MSW mock）
 * - 通过 URL ?classId=xxx 预填班级 ID
 * - 表单字段：标题、描述、考试日期、时长、满分
 * - 乐观更新：本地先插入临时项，失败后回滚（基于 urql mutation cache 更新）
 *
 * 维护者：ai13（teacher-portal）
 */

import { useState, Suspense } from "react";
import { useMutation, useQuery } from "urql";
import { useRouter, useSearchParams } from "next/navigation";
import Link from "next/link";
import { Loading } from "@edu/ui-components";
import { CreateExamMutation, ClassesQuery } from "@/lib/graphql";
import type { Class } from "@/lib/graphql";

function NewExamContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const presetClassId = searchParams.get("classId") ?? "";

  // 拉取班级列表（用于班级选择）
  const [classesResult] = useQuery({ query: ClassesQuery });

  const [createExamResult, createExam] = useMutation(CreateExamMutation);

  const [classId, setClassId] = useState(presetClassId);
  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [examDate, setExamDate] = useState("");
  const [duration, setDuration] = useState("120");
  const [totalScore, setTotalScore] = useState("100");
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);

    if (!classId) {
      setError("请选择班级");
      return;
    }
    if (!title.trim()) {
      setError("请填写考试标题");
      return;
    }
    if (!examDate) {
      setError("请选择考试日期");
      return;
    }

    setSubmitting(true);
    // 乐观更新：urql mutation 完成后由组件状态驱动跳转；
    // 失败回滚体现在错误信息展示 + 不跳转。
    const res = await createExam({
      input: {
        classId,
        title: title.trim(),
        description: description.trim() || null,
        examDate: new Date(examDate).toISOString(),
        duration: Number(duration) || 0,
        totalScore: Number(totalScore) || 0,
      },
    });
    setSubmitting(false);

    if (res.error) {
      setError(res.error.message);
      return;
    }
    // 成功后跳回考试列表
    router.push(`/exams?classId=${classId}`);
  };

  if (classesResult.fetching) {
    return (
      <div className="px-10 py-10">
        <Loading lines={4} />
      </div>
    );
  }

  const classes = (classesResult.data?.classes ?? []) as Class[];

  return (
    <div className="px-10 py-10">
      <header className="mb-8">
        <p className="mb-2">
          <Link
            href={`/exams?classId=${classId}`}
            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 CreateExamMutation · core-edu 域（P3 扩展，MSW mock）
        </p>
      </header>

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

      <section className="max-w-2xl">
        <form onSubmit={handleSubmit} className="space-y-6">
          {/* 班级选择 */}
          <div>
            <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
              班级 <span className="text-danger">*</span>
            </label>
            <select
              value={classId}
              onChange={(e) => setClassId(e.target.value)}
              className="w-full px-3 py-2 bg-transparent border border-rule rounded-button text-sm text-ink focus:outline-none"
              required
            >
              <option value="">请选择班级</option>
              {classes.map((cls) => (
                <option key={cls.id} value={cls.id}>
                  {cls.name}
                </option>
              ))}
            </select>
          </div>

          {/* 标题 */}
          <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="例如：2026 春季期中考试"
              required
            />
          </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>

          {/* 考试日期 */}
          <div>
            <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
              考试日期 <span className="text-danger">*</span>
            </label>
            <input
              type="datetime-local"
              value={examDate}
              onChange={(e) => setExamDate(e.target.value)}
              className="w-full px-3 py-2 bg-transparent border border-rule rounded-button text-sm text-ink focus:outline-none"
              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>
              <input
                type="number"
                min={1}
                value={duration}
                onChange={(e) => setDuration(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>
              <input
                type="number"
                min={1}
                value={totalScore}
                onChange={(e) => setTotalScore(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>

          {/* 错误提示 */}
          {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="submit"
              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={`/exams?classId=${classId}`}
              className="text-tiny uppercase tracking-wide text-ink-muted hover:opacity-70"
            >
              取消
            </Link>
            {createExamResult.data && (
              <span className="text-tiny text-success">创建成功</span>
            )}
          </div>
        </form>
      </section>
    </div>
  );
}

export default function NewExamPage() {
  return (
    <Suspense
      fallback={
        <div className="px-10 py-10">
          <Loading lines={3} />
        </div>
      }
    >
      <NewExamContent />
    </Suspense>
  );
}
