"use client";

/**
 * 编辑选修课页
 *
 * 数据来源（P7 扩展，MSW mock）：
 * - GraphQL ElectiveCourseDetailQuery：按 id 拉取详情（含学生列表）
 * - GraphQL UpdateElectiveCourseMutation / PublishElectiveCourseMutation / CancelElectiveCourseMutation
 *
 * 布局：
 * - 顶部：返回链接 + 标题
 * - 表单：课程名/学科/年级/容量/学期/描述
 * - 学生选课列表
 * - 越权校验：判断 teacherId 是否为当前用户
 * - "保存"/"发布"/"取消课程" 按钮
 *
 * 维护者：ai13（teacher-portal）
 */

import { useState, useEffect } from "react";
import { useQuery, useMutation } from "urql";
import { useParams } from "next/navigation";
import Link from "next/link";
import { Loading, Empty } from "@edu/ui-components";
import {
  ElectiveCourseDetailQuery,
  UpdateElectiveCourseMutation,
  PublishElectiveCourseMutation,
  CancelElectiveCourseMutation,
} from "@/lib/graphql-p7-advanced";
import type { ElectiveStudent } from "@/lib/graphql-p7-advanced";
import { CURRENT_TEACHER_ID } from "@/mocks/fixtures/elective";

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

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

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

/** 状态中文映射 */
const STATUS_LABEL: Record<string, string> = {
  draft: "草稿",
  open: "开放选课",
  closed: "已截止",
  cancelled: "已取消",
};

export default function EditElectivePage(): React.ReactNode {
  const params = useParams<{ id: string }>();
  const courseId = params?.id ?? "";

  const [result, reexecuteQuery] = useQuery({
    query: ElectiveCourseDetailQuery,
    variables: { id: courseId },
    pause: !courseId,
  });

  const [, updateCourse] = useMutation(UpdateElectiveCourseMutation);
  const [, publishCourse] = useMutation(PublishElectiveCourseMutation);
  const [, cancelCourse] = useMutation(CancelElectiveCourseMutation);

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

  const course = result.data?.electiveCourseDetail;
  // 越权校验：教师只能编辑自己教授的课程
  const isOwner = course?.teacherId === CURRENT_TEACHER_ID;

  // 初始化表单
  useEffect(() => {
    if (!course) return;
    setTitle(course.title);
    setSubject(course.subject);
    setGrade(course.grade);
    setCapacity(String(course.capacity));
    setSemester(course.semester);
    setDescription(course.description ?? "");
  }, [course]);

  /** 保存更新 */
  const handleSave = async () => {
    if (!course) return;
    setError(null);
    setMsg(null);
    setSubmitting(true);
    const res = await updateCourse({
      input: {
        id: course.id,
        title: title.trim(),
        subject,
        grade,
        capacity: Number(capacity) || 0,
        semester,
        description: description.trim() || null,
      },
    });
    setSubmitting(false);
    if (res.error) {
      setError(res.error.message);
      return;
    }
    setMsg("已保存");
    reexecuteQuery({ requestPolicy: "network-only" });
  };

  /** 发布选修课 */
  const handlePublish = async () => {
    if (!course) return;
    setError(null);
    setMsg(null);
    setSubmitting(true);
    const res = await publishCourse({ id: course.id });
    setSubmitting(false);
    if (res.error) {
      setError(res.error.message);
      return;
    }
    setMsg("已发布");
    reexecuteQuery({ requestPolicy: "network-only" });
  };

  /** 取消选修课 */
  const handleCancel = async () => {
    if (!course) return;
    setError(null);
    setMsg(null);
    if (!window.confirm("确认取消此选修课？取消后无法恢复。")) return;
    setSubmitting(true);
    const res = await cancelCourse({ id: course.id });
    setSubmitting(false);
    if (res.error) {
      setError(res.error.message);
      return;
    }
    setMsg("已取消");
    reexecuteQuery({ requestPolicy: "network-only" });
  };

  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 ElectiveCourseDetailQuery + UpdateElectiveCourseMutation · core-edu 域（P7 扩展，MSW mock）
        </p>
      </header>

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

      {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>
      ) : !course ? (
        <Empty title="未找到选修课" description="该选修课不存在或已被删除" />
      ) : !isOwner ? (
        <Empty
          title="无权编辑"
          description="只能编辑本人教授的选修课"
        />
      ) : (
        <section className="max-w-4xl space-y-10">
          {/* 表单 */}
          <div className="max-w-2xl space-y-6">
            <div className="flex items-baseline justify-between mb-2">
              <span className="text-tiny uppercase tracking-wide text-ink-muted">
                当前状态：
                <span className="ml-2 text-ink">
                  {STATUS_LABEL[course.status] ?? course.status}
                </span>
              </span>
            </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"
                required
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
                  学科
                </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">
                  年级
                </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">
                  容量
                </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"
                />
              </div>
              <div>
                <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
                  学期
                </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"
              />
            </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>
            )}
            {msg && (
              <p className="text-tiny text-success">{msg}</p>
            )}

            <div className="flex items-center gap-4 pt-4">
              <button
                type="button"
                onClick={handleSave}
                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>
              {course.status !== "open" && course.status !== "cancelled" && (
                <button
                  type="button"
                  onClick={handlePublish}
                  disabled={submitting}
                  className="px-4 py-2 text-sm text-ink bg-transparent border border-accent text-accent rounded-button hover:bg-subtle disabled:opacity-50"
                >
                  发布
                </button>
              )}
              {course.status !== "cancelled" && (
                <button
                  type="button"
                  onClick={handleCancel}
                  disabled={submitting}
                  className="px-4 py-2 text-sm text-danger bg-transparent border border-danger rounded-button hover:bg-subtle disabled:opacity-50"
                >
                  取消课程
                </button>
              )}
            </div>
          </div>

          {/* 学生选课列表 */}
          <div>
            <h3 className="text-xl font-serif text-ink mb-2">
              选课学生
              <span className="ml-2 text-sm font-sans text-ink-muted">
                {course.students.length} 人
              </span>
            </h3>
            <div className="rule-thin mb-4" />

            {course.students.length === 0 ? (
              <Empty title="暂无选课学生" description="尚未开放选课或无人选课" />
            ) : (
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b border-rule text-left">
                    <th className="py-3 px-2 text-tiny uppercase tracking-wide text-ink-muted">
                      学号
                    </th>
                    <th className="py-3 px-2 text-tiny uppercase tracking-wide text-ink-muted">
                      姓名
                    </th>
                    <th className="py-3 px-2 text-tiny uppercase tracking-wide text-ink-muted">
                      选课时间
                    </th>
                    <th className="py-3 px-2 text-tiny uppercase tracking-wide text-ink-muted">
                      状态
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {course.students.map((stu: ElectiveStudent) => (
                    <tr
                      key={stu.studentId}
                      className="border-b border-rule hover:bg-subtle"
                    >
                      <td className="py-3 px-2 font-mono text-tiny text-ink">
                        {stu.studentNo}
                      </td>
                      <td className="py-3 px-2 text-ink">{stu.studentName}</td>
                      <td className="py-3 px-2 text-ink-muted text-tiny">
                        {new Date(stu.enrolledAt).toLocaleString("zh-CN")}
                      </td>
                      <td className="py-3 px-2">
                        <span
                          className="text-tiny"
                          style={{
                            color:
                              stu.status === "enrolled"
                                ? "var(--color-success)"
                                : "var(--color-danger)",
                          }}
                        >
                          {stu.status === "enrolled" ? "已选" : "已退选"}
                        </span>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
        </section>
      )}
    </div>
  );
}
