"use client";

/**
 * 布置作业表单页
 *
 * 数据来源（contract.md §2.4）：GraphQL AssignHomeworkMutation（P3 扩展，MSW mock）
 * - 通过 URL ?classId=xxx 预填班级 ID
 * - 表单字段：班级选择、标题、描述、截止日期
 * - 乐观更新：成功后跳回列表；失败展示错误并保留输入
 *
 * 维护者：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 { AssignHomeworkMutation, ClassesQuery } from "@/lib/graphql";
import type { Class } from "@/lib/graphql";

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

  const [classesResult] = useQuery({ query: ClassesQuery });
  const [assignResult, assignHomework] = useMutation(AssignHomeworkMutation);

  const [classId, setClassId] = useState(presetClassId);
  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [dueDate, setDueDate] = useState("");
  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 (!dueDate) {
      setError("请选择截止日期");
      return;
    }

    setSubmitting(true);
    const res = await assignHomework({
      input: {
        classId,
        title: title.trim(),
        description: description.trim() || null,
        dueDate: new Date(dueDate).toISOString(),
      },
    });
    setSubmitting(false);

    if (res.error) {
      setError(res.error.message);
      return;
    }
    router.push(`/homework?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={`/homework?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 AssignHomeworkMutation · 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="例如：函数练习题"
              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={dueDate}
              onChange={(e) => setDueDate(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>

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

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