"use client";

/**
 * 课程计划列表页（P7-insights）
 *
 * 数据来源：GraphQL CoursePlansQuery + CreateCoursePlanMutation
 *
 * 功能：
 * - 状态筛选（draft/published/archived）
 * - 列表：标题/学科/年级/学年/状态/操作
 * - "新建课程计划" 弹窗（模态框）
 *
 * 维护者：ai13（teacher-portal）
 */

import { useState } from "react";
import { useQuery, useMutation } from "urql";
import Link from "next/link";
import { Loading, Empty } from "@edu/ui-components";
import {
  CoursePlansQuery,
  CreateCoursePlanMutation,
} from "@/lib/graphql-p7-insights";
import type {
  CoursePlanItem,
  CoursePlanStatus,
  CreateCoursePlanInput,
} from "@/lib/graphql-p7-insights";

type StatusFilter = "ALL" | CoursePlanStatus;

const STATUS_OPTIONS: { value: StatusFilter; label: string }[] = [
  { value: "ALL", label: "全部" },
  { value: "DRAFT", label: "草稿" },
  { value: "PUBLISHED", label: "已发布" },
  { value: "ARCHIVED", label: "已归档" },
];

const STATUS_LABEL: Record<CoursePlanStatus, string> = {
  DRAFT: "草稿",
  PUBLISHED: "已发布",
  ARCHIVED: "已归档",
};

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

function formatDate(iso: string): string {
  return iso.slice(0, 16).replace("T", " ");
}

export default function CoursePlansPage(): JSX.Element {
  const [status, setStatus] = useState<StatusFilter>("ALL");
  const [modalOpen, setModalOpen] = useState(false);
  const [creating, setCreating] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [result] = useQuery({
    query: CoursePlansQuery,
    variables: status === "ALL" ? {} : { status },
  });

  const [, createCoursePlan] = useMutation(CreateCoursePlanMutation);

  // 新建表单 state
  const [form, setForm] = useState<{
    title: string;
    subject: string;
    grade: string;
    academicYear: string;
    semester: string;
    totalHours: number;
    textbookId: string;
  }>({
    title: "",
    subject: SUBJECTS[0] ?? "数学",
    grade: GRADES[0] ?? "小学三年级",
    academicYear: "2026-2027",
    semester: "上学期",
    totalHours: 48,
    textbookId: "",
  });

  const plans: CoursePlanItem[] = result.data?.coursePlans ?? [];

  const handleCreate = async (): Promise<void> => {
    if (!form.title) {
      setError("请填写标题");
      return;
    }
    setCreating(true);
    setError(null);
    const input: CreateCoursePlanInput = {
      title: form.title,
      subject: form.subject,
      grade: form.grade,
      academicYear: form.academicYear,
      semester: form.semester,
      totalHours: form.totalHours,
      textbookId: form.textbookId || null,
    };
    const res = await createCoursePlan({ input });
    setCreating(false);
    if (res.error || !res.data?.createCoursePlan) {
      setError(res.error?.message ?? "创建失败");
      return;
    }
    setModalOpen(false);
    setForm((prev) => ({ ...prev, title: "" }));
  };

  return (
    <div className="px-10 py-10">
      <header className="mb-8">
        <h1 className="text-3xl font-serif text-ink">课程计划</h1>
        <p className="mt-1 text-sm text-ink-muted">
          GraphQL CoursePlansQuery · 学期/学年课程计划管理（P7-insights，MSW mock）
        </p>
      </header>

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

      {/* 工具栏 */}
      <div className="mb-6 flex items-baseline justify-between flex-wrap gap-4">
        <div className="flex items-center gap-3">
          <label className="text-tiny uppercase tracking-wide text-ink-muted">
            状态
          </label>
          <select
            value={status}
            onChange={(e) => setStatus(e.target.value as StatusFilter)}
            className="px-3 py-2 bg-transparent border-b border-rule text-sm font-sans text-ink focus:outline-none focus:border-accent"
          >
            {STATUS_OPTIONS.map((s) => (
              <option key={s.value} value={s.value}>
                {s.label}
              </option>
            ))}
          </select>
        </div>
        <button
          type="button"
          onClick={() => setModalOpen(true)}
          className="px-4 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover"
        >
          新建课程计划
        </button>
      </div>

      {result.fetching ? (
        <Loading lines={5} />
      ) : 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>
      ) : plans.length === 0 ? (
        <Empty
          title="暂无课程计划"
          description="点击右上角「新建课程计划」开始创建"
        />
      ) : (
        <table className="w-full text-sm">
          <thead>
            <tr className="text-left text-tiny uppercase tracking-wide text-ink-muted border-b border-rule">
              <th className="py-3 pr-4 font-normal">标题</th>
              <th className="py-3 pr-4 font-normal">学科</th>
              <th className="py-3 pr-4 font-normal">年级</th>
              <th className="py-3 pr-4 font-normal">学年</th>
              <th className="py-3 pr-4 font-normal">学期</th>
              <th className="py-3 pr-4 font-normal">学时</th>
              <th className="py-3 pr-4 font-normal">状态</th>
              <th className="py-3 pr-4 font-normal">更新时间</th>
              <th className="py-3 pr-4 font-normal text-right">操作</th>
            </tr>
          </thead>
          <tbody>
            {plans.map((p) => (
              <tr key={p.id} className="border-b border-rule">
                <td className="py-3 pr-4">
                  <Link
                    href={`/course-plans/${p.id}`}
                    className="font-serif text-ink hover:text-accent"
                  >
                    {p.title}
                  </Link>
                </td>
                <td className="py-3 pr-4 text-ink">{p.subject}</td>
                <td className="py-3 pr-4 text-ink">{p.grade}</td>
                <td className="py-3 pr-4 text-ink-muted font-mono text-tiny">
                  {p.academicYear}
                </td>
                <td className="py-3 pr-4 text-ink">{p.semester}</td>
                <td className="py-3 pr-4 text-ink-muted font-mono text-tiny">
                  {p.totalHours}
                </td>
                <td className="py-3 pr-4">
                  <span className="px-2 py-0.5 rounded bg-subtle text-tiny text-ink">
                    {STATUS_LABEL[p.status]}
                  </span>
                </td>
                <td className="py-3 pr-4 text-ink-muted font-mono text-tiny">
                  {formatDate(p.updatedAt)}
                </td>
                <td className="py-3 pr-4 text-right">
                  <Link
                    href={`/course-plans/${p.id}`}
                    className="text-tiny uppercase tracking-wide text-accent hover:opacity-70"
                  >
                    查看
                  </Link>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      )}

      {/* 新建弹窗 */}
      {modalOpen && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center"
          style={{ background: "hsl(var(--ink) / 0.4)" }}
          role="dialog"
          aria-modal="true"
          aria-label="新建课程计划"
        >
          <div className="w-full max-w-lg p-6 border border-rule rounded-card bg-paper">
            <h2 className="text-xl font-serif text-ink mb-4">新建课程计划</h2>
            <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={form.title}
                  onChange={(e) =>
                    setForm((prev) => ({ ...prev, title: e.target.value }))
                  }
                  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={form.subject}
                  onChange={(e) =>
                    setForm((prev) => ({ ...prev, subject: 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={form.grade}
                  onChange={(e) =>
                    setForm((prev) => ({ ...prev, grade: 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="flex flex-col gap-1">
                <span className="text-tiny uppercase tracking-wide text-ink-muted">
                  学年
                </span>
                <input
                  type="text"
                  value={form.academicYear}
                  onChange={(e) =>
                    setForm((prev) => ({ ...prev, academicYear: e.target.value }))
                  }
                  className="px-3 py-2 bg-transparent border-b border-rule text-sm text-ink font-mono"
                />
              </label>
              <label className="flex flex-col gap-1">
                <span className="text-tiny uppercase tracking-wide text-ink-muted">
                  学期
                </span>
                <select
                  value={form.semester}
                  onChange={(e) =>
                    setForm((prev) => ({ ...prev, semester: e.target.value }))
                  }
                  className="px-3 py-2 bg-transparent border-b border-rule text-sm text-ink"
                >
                  <option value="上学期">上学期</option>
                  <option value="下学期">下学期</option>
                </select>
              </label>
              <label className="flex flex-col gap-1">
                <span className="text-tiny uppercase tracking-wide text-ink-muted">
                  总学时
                </span>
                <input
                  type="number"
                  value={form.totalHours}
                  onChange={(e) =>
                    setForm((prev) => ({
                      ...prev,
                      totalHours: Number(e.target.value) || 0,
                    }))
                  }
                  className="px-3 py-2 bg-transparent border-b border-rule text-sm text-ink font-mono"
                />
              </label>
              <label className="flex flex-col gap-1">
                <span className="text-tiny uppercase tracking-wide text-ink-muted">
                  教材 ID（可选）
                </span>
                <input
                  type="text"
                  value={form.textbookId}
                  onChange={(e) =>
                    setForm((prev) => ({ ...prev, textbookId: e.target.value }))
                  }
                  className="px-3 py-2 bg-transparent border-b border-rule text-sm text-ink font-mono"
                />
              </label>
            </div>

            {error && (
              <p className="mt-3 text-sm text-danger">{error}</p>
            )}

            <div className="mt-6 flex justify-end gap-3">
              <button
                type="button"
                onClick={() => setModalOpen(false)}
                className="px-4 py-2 text-sm text-ink border border-rule rounded-button hover:bg-subtle"
              >
                取消
              </button>
              <button
                type="button"
                onClick={handleCreate}
                disabled={creating}
                className="px-4 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover disabled:opacity-50"
              >
                {creating ? "创建中…" : "创建"}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
