"use client";

/**
 * 调课申请页 - 教师调课申请管理
 *
 * 数据来源（P7 扩展，MSW mock）：
 * - GraphQL ScheduleChangesQuery：调课申请列表 + 分页
 * - GraphQL SubmitScheduleChangeMutation：提交调课/代课申请
 *
 * 功能：
 * - 状态筛选（全部/待审批/已批准/已拒绝）
 * - 类型筛选（全部/调课/代课）
 * - 提交调课申请模态框（原班级/原日期/原节次/调整后日期/类型/代课教师/原因）
 * - 状态徽章（待审批黄/已批准绿/已拒绝红）
 *
 * 维护者：ai13（teacher-portal）
 */

import { useState, useMemo } from "react";
import { useQuery, useMutation } from "urql";
import { Loading, Empty } from "@edu/ui-components";
import { ClassesQuery } from "@/lib/graphql";
import type { Class } from "@/lib/graphql";
import {
  ScheduleChangesQuery,
  SubmitScheduleChangeMutation,
} from "@/lib/graphql-p7-admin";
import type {
  ScheduleChange,
  ScheduleChangeType,
  ScheduleChangeStatus,
  SubmitScheduleChangeInput,
} from "@/lib/graphql-p7-admin";
import {
  SCHEDULE_CHANGE_TYPE_LABEL,
  SCHEDULE_CHANGE_STATUS_LABEL,
} from "@/mocks/fixtures/leave-requests";

const TYPE_FILTERS: { value: ScheduleChangeType | "ALL"; label: string }[] = [
  { value: "ALL", label: "全部" },
  { value: "ADJUST", label: "调课" },
  { value: "SUBSTITUTE", label: "代课" },
];

const STATUS_FILTERS: {
  value: ScheduleChangeStatus | "ALL";
  label: string;
}[] = [
  { value: "ALL", label: "全部" },
  { value: "PENDING", label: "待审批" },
  { value: "APPROVED", label: "已批准" },
  { value: "REJECTED", label: "已拒绝" },
];

const PERIOD_OPTIONS = [1, 2, 3, 4, 5, 6, 7, 8];

const SUBJECT_OPTIONS = [
  "数学",
  "语文",
  "英语",
  "物理",
  "化学",
  "生物",
] as const;

function statusBadgeClass(status: ScheduleChangeStatus): string {
  switch (status) {
    case "PENDING":
      return "text-warning border-warning";
    case "APPROVED":
      return "text-success border-success";
    case "REJECTED":
      return "text-danger border-danger";
    default:
      return "text-ink-muted border-rule";
  }
}

function todayStr(): string {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
}

function dateOffset(days: number): string {
  const d = new Date();
  d.setDate(d.getDate() + days);
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
}

export default function ScheduleChangesPage(): React.ReactNode {
  const [typeFilter, setTypeFilter] = useState<ScheduleChangeType | "ALL">(
    "ALL",
  );
  const [statusFilter, setStatusFilter] = useState<
    ScheduleChangeStatus | "ALL"
  >("ALL");
  const [page, setPage] = useState(1);
  const pageSize = 20;

  // 提交对话框状态
  const [showSubmit, setShowSubmit] = useState(false);
  const [formClassId, setFormClassId] = useState("");
  const [formOriginalDate, setFormOriginalDate] = useState(todayStr());
  const [formOriginalPeriod, setFormOriginalPeriod] = useState(1);
  const [formOriginalSubject, setFormOriginalSubject] = useState<string>(
    SUBJECT_OPTIONS[0] ?? "数学",
  );
  const [formAdjustedDate, setFormAdjustedDate] = useState(dateOffset(1));
  const [formAdjustedPeriod, setFormAdjustedPeriod] = useState(1);
  const [formAdjustedSubject, setFormAdjustedSubject] = useState<string>(
    SUBJECT_OPTIONS[0] ?? "数学",
  );
  const [formType, setFormType] = useState<ScheduleChangeType>("ADJUST");
  const [formSubstituteTeacherId, setFormSubstituteTeacherId] = useState("");
  const [formReason, setFormReason] = useState("");
  const [formSubmitting, setFormSubmitting] = useState(false);
  const [formError, setFormError] = useState<string | null>(null);
  const [formSuccess, setFormSuccess] = useState<string | null>(null);

  const [classesResult] = useQuery({ query: ClassesQuery });
  const classes: Class[] = classesResult.data?.classes ?? [];
  const firstClassId = classes[0]?.id ?? "";

  const [result, reexecute] = useQuery({
    query: ScheduleChangesQuery,
    variables: { page, pageSize },
  });

  const [, submitChange] = useMutation(SubmitScheduleChangeMutation);

  const data = result.data?.scheduleChanges;
  const allItems: ScheduleChange[] = data?.items ?? [];
  const total = data?.total ?? 0;

  // 客户端二次筛选（type/status）
  const filteredItems = useMemo(() => {
    return allItems.filter((item) => {
      if (typeFilter !== "ALL" && item.type !== typeFilter) return false;
      if (statusFilter !== "ALL" && item.status !== statusFilter) return false;
      return true;
    });
  }, [allItems, typeFilter, statusFilter]);

  const handleSubmit = async (): Promise<void> => {
    const targetClassId = formClassId || firstClassId;
    if (!targetClassId) {
      setFormError("请选择班级");
      return;
    }
    if (!formOriginalDate || !formAdjustedDate) {
      setFormError("请填写原日期和调整后日期");
      return;
    }
    if (!formReason.trim()) {
      setFormError("请填写调课原因");
      return;
    }
    setFormSubmitting(true);
    setFormError(null);
    setFormSuccess(null);
    const input: SubmitScheduleChangeInput = {
      classId: targetClassId,
      originalDate: formOriginalDate,
      originalPeriod: formOriginalPeriod,
      originalSubject: formOriginalSubject,
      adjustedDate: formAdjustedDate,
      adjustedPeriod: formAdjustedPeriod,
      adjustedSubject: formAdjustedSubject,
      substituteTeacherId: formSubstituteTeacherId.trim() || null,
      type: formType,
      reason: formReason.trim(),
    };
    const res = await submitChange({ input });
    setFormSubmitting(false);
    if (res.error) {
      setFormError(res.error.message);
      return;
    }
    setFormSuccess(
      `已提交：${res.data?.submitScheduleChange?.requestId ?? "—"}，等待审批`,
    );
    // 重置表单
    setFormReason("");
    reexecute({ requestPolicy: "network-only" });
  };

  const closeSubmit = (): void => {
    setShowSubmit(false);
    setFormError(null);
    setFormSuccess(null);
    setFormReason("");
  };

  return (
    <div className="px-10 py-10">
      <header className="mb-8 flex items-baseline justify-between">
        <div>
          <h1 className="text-3xl font-serif text-ink">调课申请</h1>
          <p className="mt-1 text-sm text-ink-muted">
            GraphQL ScheduleChangesQuery + SubmitScheduleChangeMutation（P7
            扩展，MSW mock）
          </p>
        </div>
        <button
          type="button"
          onClick={() => {
            setShowSubmit(true);
            setFormSuccess(null);
          }}
          className="px-4 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover"
        >
          提交调课申请
        </button>
      </header>

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

      {/* 筛选栏 */}
      <section className="mb-8">
        <div className="flex items-center justify-between flex-wrap gap-4">
          <div className="flex items-center gap-2 flex-wrap">
            <label className="text-tiny uppercase tracking-wide text-ink-muted">
              类型：
            </label>
            {TYPE_FILTERS.map((t) => {
              const active = typeFilter === t.value;
              return (
                <button
                  key={t.value}
                  type="button"
                  onClick={() => setTypeFilter(t.value)}
                  className={`px-3 py-1 text-tiny uppercase tracking-wide rounded-button border transition-colors ${
                    active
                      ? "bg-accent text-ink-on-accent border-accent"
                      : "bg-transparent text-ink-muted border-rule hover:text-ink"
                  }`}
                >
                  {t.label}
                </button>
              );
            })}
          </div>
          <div className="flex items-center gap-2 flex-wrap">
            <label className="text-tiny uppercase tracking-wide text-ink-muted">
              状态：
            </label>
            {STATUS_FILTERS.map((s) => {
              const active = statusFilter === s.value;
              return (
                <button
                  key={s.value}
                  type="button"
                  onClick={() => setStatusFilter(s.value)}
                  className={`px-3 py-1 text-tiny uppercase tracking-wide rounded-button border transition-colors ${
                    active
                      ? "bg-accent text-ink-on-accent border-accent"
                      : "bg-transparent text-ink-muted border-rule hover:text-ink"
                  }`}
                >
                  {s.label}
                </button>
              );
            })}
          </div>
        </div>
      </section>

      {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>
      ) : filteredItems.length === 0 ? (
        <Empty title="暂无调课申请" description="当前筛选条件下没有记录" />
      ) : (
        <section>
          <div className="flex items-baseline justify-between mb-4">
            <h2 className="text-xl font-serif text-ink">
              申请列表
              <span className="ml-2 text-sm font-sans text-ink-muted">
                共 {filteredItems.length} 条（总计 {total}）
              </span>
            </h2>
          </div>
          <div className="rule-thin mb-4" />
          <div className="border border-rule rounded-card overflow-hidden">
            <table className="w-full text-sm">
              <thead className="bg-subtle">
                <tr>
                  <th className="px-4 py-3 text-left text-tiny uppercase tracking-wide text-ink-muted">
                    申请人
                  </th>
                  <th className="px-4 py-3 text-left text-tiny uppercase tracking-wide text-ink-muted">
                    班级
                  </th>
                  <th className="px-4 py-3 text-left text-tiny uppercase tracking-wide text-ink-muted">
                    原课程
                  </th>
                  <th className="px-4 py-3 text-left text-tiny uppercase tracking-wide text-ink-muted">
                    调整后
                  </th>
                  <th className="px-4 py-3 text-left text-tiny uppercase tracking-wide text-ink-muted">
                    类型
                  </th>
                  <th className="px-4 py-3 text-left text-tiny uppercase tracking-wide text-ink-muted">
                    原因
                  </th>
                  <th className="px-4 py-3 text-left text-tiny uppercase tracking-wide text-ink-muted">
                    状态
                  </th>
                </tr>
              </thead>
              <tbody>
                {filteredItems.map((r) => (
                  <tr key={r.id} className="border-t border-rule">
                    <td className="px-4 py-3">
                      <p className="font-serif text-ink">{r.requesterName}</p>
                      {r.substituteTeacherName && (
                        <p className="text-tiny text-ink-muted">
                          代课：{r.substituteTeacherName}
                        </p>
                      )}
                    </td>
                    <td className="px-4 py-3 text-sm text-ink">
                      {r.className}
                    </td>
                    <td className="px-4 py-3 font-mono text-tiny text-ink-muted">
                      <p>{r.originalDate}</p>
                      <p>
                        第 {r.originalPeriod} 节 · {r.originalSubject}
                      </p>
                    </td>
                    <td className="px-4 py-3 font-mono text-tiny text-ink-muted">
                      <p>{r.adjustedDate}</p>
                      <p>
                        第 {r.adjustedPeriod} 节 · {r.adjustedSubject}
                      </p>
                    </td>
                    <td className="px-4 py-3 text-sm text-ink">
                      {SCHEDULE_CHANGE_TYPE_LABEL[r.type]}
                    </td>
                    <td className="px-4 py-3 text-tiny text-ink-muted max-w-xs">
                      <p className="truncate">{r.reason}</p>
                      {r.reviewComment && (
                        <p className="mt-1 text-tiny text-ink-subtle">
                          审批：{r.reviewComment}
                        </p>
                      )}
                    </td>
                    <td className="px-4 py-3">
                      <span
                        className={`inline-block px-2 py-0.5 rounded-button text-tiny font-mono border ${statusBadgeClass(
                          r.status,
                        )}`}
                      >
                        {SCHEDULE_CHANGE_STATUS_LABEL[r.status]}
                      </span>
                      {r.reviewedAt && (
                        <p className="mt-1 text-tiny font-mono text-ink-muted">
                          {r.reviewedAt.slice(0, 10)}
                        </p>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* 分页 */}
          <div className="mt-6 flex items-center justify-between">
            <button
              type="button"
              onClick={() => setPage((p) => Math.max(1, p - 1))}
              disabled={page <= 1}
              className="px-4 py-2 text-sm text-ink border border-rule rounded-button hover:bg-subtle disabled:opacity-40 disabled:cursor-not-allowed"
            >
              上一页
            </button>
            <span className="text-tiny text-ink-muted">
              第 {page} 页（每页 {pageSize} 条）
            </span>
            <button
              type="button"
              onClick={() => setPage((p) => p + 1)}
              disabled={allItems.length < pageSize}
              className="px-4 py-2 text-sm text-ink border border-rule rounded-button hover:bg-subtle disabled:opacity-40 disabled:cursor-not-allowed"
            >
              下一页
            </button>
          </div>
        </section>
      )}

      {/* 提交调课对话框 */}
      {showSubmit && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center"
          style={{ background: "hsl(var(--color-ink) / 0.3)" }}
          role="dialog"
          aria-modal="true"
        >
          <div className="w-full max-w-2xl p-8 bg-paper border border-rule rounded-card max-h-[90vh] overflow-y-auto">
            <div className="flex items-baseline justify-between mb-4">
              <h3 className="text-xl font-serif text-ink">提交调课申请</h3>
              <button
                type="button"
                onClick={closeSubmit}
                className="text-tiny text-ink-muted hover:opacity-70"
              >
                关闭
              </button>
            </div>
            <div className="rule-thin mb-4" />
            {formSuccess ? (
              <div className="mb-4 p-4 border border-rule rounded-card bg-subtle">
                <p className="text-sm text-success">{formSuccess}</p>
                <button
                  type="button"
                  onClick={() => setFormSuccess(null)}
                  className="mt-2 text-tiny text-accent hover:opacity-70"
                >
                  再提交一条
                </button>
              </div>
            ) : null}

            {/* 班级 + 类型 */}
            <div className="mb-4 grid grid-cols-2 gap-4">
              <div>
                <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
                  班级
                </label>
                <select
                  value={formClassId || firstClassId}
                  onChange={(e) => setFormClassId(e.target.value)}
                  className="w-full px-3 py-2 bg-transparent border-b border-rule text-sm font-sans text-ink focus:outline-none focus:border-accent"
                >
                  {classes.map((c) => (
                    <option key={c.id} value={c.id}>
                      {c.name}
                    </option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
                  类型
                </label>
                <select
                  value={formType}
                  onChange={(e) =>
                    setFormType(e.target.value as ScheduleChangeType)
                  }
                  className="w-full px-3 py-2 bg-transparent border-b border-rule text-sm font-sans text-ink focus:outline-none focus:border-accent"
                >
                  <option value="ADJUST">调课</option>
                  <option value="SUBSTITUTE">代课</option>
                </select>
              </div>
            </div>

            {/* 原课程 */}
            <div className="mb-4 p-4 border border-rule rounded-card bg-surface">
              <p className="mb-3 text-tiny uppercase tracking-wide text-ink-muted">
                原课程
              </p>
              <div className="grid grid-cols-3 gap-4">
                <div>
                  <label className="block text-tiny text-ink-muted mb-1">
                    日期
                  </label>
                  <input
                    type="date"
                    value={formOriginalDate}
                    onChange={(e) => setFormOriginalDate(e.target.value)}
                    className="w-full px-3 py-2 bg-transparent border-b border-rule text-sm font-mono text-ink focus:outline-none focus:border-accent"
                  />
                </div>
                <div>
                  <label className="block text-tiny text-ink-muted mb-1">
                    节次
                  </label>
                  <select
                    value={formOriginalPeriod}
                    onChange={(e) =>
                      setFormOriginalPeriod(Number(e.target.value))
                    }
                    className="w-full px-3 py-2 bg-transparent border-b border-rule text-sm font-mono text-ink focus:outline-none focus:border-accent"
                  >
                    {PERIOD_OPTIONS.map((p) => (
                      <option key={p} value={p}>
                        第 {p} 节
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="block text-tiny text-ink-muted mb-1">
                    学科
                  </label>
                  <select
                    value={formOriginalSubject}
                    onChange={(e) => setFormOriginalSubject(e.target.value)}
                    className="w-full px-3 py-2 bg-transparent border-b border-rule text-sm font-sans text-ink focus:outline-none focus:border-accent"
                  >
                    {SUBJECT_OPTIONS.map((s) => (
                      <option key={s} value={s}>
                        {s}
                      </option>
                    ))}
                  </select>
                </div>
              </div>
            </div>

            {/* 调整后 */}
            <div className="mb-4 p-4 border border-rule rounded-card bg-surface">
              <p className="mb-3 text-tiny uppercase tracking-wide text-ink-muted">
                调整后
              </p>
              <div className="grid grid-cols-3 gap-4">
                <div>
                  <label className="block text-tiny text-ink-muted mb-1">
                    日期
                  </label>
                  <input
                    type="date"
                    value={formAdjustedDate}
                    onChange={(e) => setFormAdjustedDate(e.target.value)}
                    className="w-full px-3 py-2 bg-transparent border-b border-rule text-sm font-mono text-ink focus:outline-none focus:border-accent"
                  />
                </div>
                <div>
                  <label className="block text-tiny text-ink-muted mb-1">
                    节次
                  </label>
                  <select
                    value={formAdjustedPeriod}
                    onChange={(e) =>
                      setFormAdjustedPeriod(Number(e.target.value))
                    }
                    className="w-full px-3 py-2 bg-transparent border-b border-rule text-sm font-mono text-ink focus:outline-none focus:border-accent"
                  >
                    {PERIOD_OPTIONS.map((p) => (
                      <option key={p} value={p}>
                        第 {p} 节
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="block text-tiny text-ink-muted mb-1">
                    学科
                  </label>
                  <select
                    value={formAdjustedSubject}
                    onChange={(e) => setFormAdjustedSubject(e.target.value)}
                    className="w-full px-3 py-2 bg-transparent border-b border-rule text-sm font-sans text-ink focus:outline-none focus:border-accent"
                  >
                    {SUBJECT_OPTIONS.map((s) => (
                      <option key={s} value={s}>
                        {s}
                      </option>
                    ))}
                  </select>
                </div>
              </div>
              {formType === "SUBSTITUTE" && (
                <div className="mt-3">
                  <label className="block text-tiny text-ink-muted mb-1">
                    代课教师 ID（可选）
                  </label>
                  <input
                    type="text"
                    value={formSubstituteTeacherId}
                    onChange={(e) =>
                      setFormSubstituteTeacherId(e.target.value)
                    }
                    placeholder="例如：u-002"
                    className="w-full px-3 py-2 bg-transparent border-b border-rule text-sm font-mono text-ink focus:outline-none focus:border-accent"
                  />
                </div>
              )}
            </div>

            {/* 原因 */}
            <div className="mb-4">
              <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
                调课原因
              </label>
              <textarea
                value={formReason}
                onChange={(e) => setFormReason(e.target.value)}
                rows={3}
                placeholder="请填写调课原因"
                className="w-full px-3 py-2 bg-transparent border border-rule rounded-button text-sm text-ink focus:outline-none focus:border-accent"
              />
            </div>
            {formError && (
              <p className="mb-3 text-tiny text-danger">{formError}</p>
            )}
            <div className="flex items-center justify-end gap-3">
              <button
                type="button"
                onClick={closeSubmit}
                disabled={formSubmitting}
                className="px-4 py-2 text-sm text-ink border border-rule rounded-button hover:bg-subtle disabled:opacity-50"
              >
                关闭
              </button>
              <button
                type="button"
                onClick={handleSubmit}
                disabled={formSubmitting}
                className="px-4 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover disabled:opacity-50"
              >
                {formSubmitting ? "提交中..." : "提交申请"}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
