"use client";

/**
 * 题库主页 - 六维筛选 + CRUD + 批量导入导出
 *
 * 数据来源（P7 扩展，MSW mock）：
 * - GraphQL QuestionsLibraryQuery：题库列表（六维筛选 + 分页 + 总数）
 * - GraphQL QuestionCreate/Update/Delete：题目 CRUD
 * - GraphQL QuestionBatchImport：批量导入
 * - GraphQL QuestionBatchExport：批量导出（查询后用 Blob 下载 JSON）
 *
 * 维护者：ai13（teacher-portal）
 */

import { useState, useMemo, useCallback, useRef, useEffect } from "react";
import { useQuery, useMutation } from "urql";
import Link from "next/link";
import { Loading, Empty } from "@edu/ui-components";
import {
  QuestionsLibraryQuery,
  QuestionCreateMutation,
  QuestionUpdateMutation,
  QuestionDeleteMutation,
  QuestionBatchImportMutation,
  QuestionBatchExportQuery,
} from "@/lib/graphql-p7-exams";
import type {
  QuestionItem,
  QuestionType,
  QuestionDifficulty,
  QuestionsLibraryFilter,
  QuestionCreateInput,
  QuestionUpdateInput,
  QuestionBatchImportItem,
} from "@/lib/graphql-p7-exams";
import { MOCK_TEXTBOOKS, MOCK_TEXTBOOK_DETAILS } from "@/mocks/fixtures/textbooks";
import {
  QUESTION_TYPE_OPTIONS,
  QUESTION_DIFFICULTY_OPTIONS,
  QUESTION_TYPE_LABEL,
  QUESTION_DIFFICULTY_LABEL,
} from "@/mocks/fixtures/questions";

/** 类型中文 */
const TYPE_LABEL: Record<QuestionType, string> = QUESTION_TYPE_LABEL;
/** 难度中文 */
const DIFFICULTY_LABEL: Record<QuestionDifficulty, string> =
  QUESTION_DIFFICULTY_LABEL;

/** 编辑/新建弹窗的表单状态 */
interface QuestionFormState {
  questionId: string | null; // null 表示新建
  content: string;
  type: QuestionType;
  difficulty: QuestionDifficulty;
  textbookId: string;
  chapterId: string;
  kpId: string;
  score: string;
  answer: string;
  analysis: string;
}

/** 初始空表单 */
function emptyForm(): QuestionFormState {
  return {
    questionId: null,
    content: "",
    type: "SINGLE_CHOICE",
    difficulty: "MEDIUM",
    textbookId: "",
    chapterId: "",
    kpId: "",
    score: "5",
    answer: "",
    analysis: "",
  };
}

/** 从 QuestionItem 填充表单 */
function fillForm(q: QuestionItem): QuestionFormState {
  return {
    questionId: q.questionId,
    content: q.content,
    type: q.type,
    difficulty: q.difficulty,
    textbookId: q.textbookId ?? "",
    chapterId: q.chapterId ?? "",
    kpId: q.kpId ?? "",
    score: String(q.score),
    answer: q.answer,
    analysis: q.analysis,
  };
}

export default function QuestionsPage(): React.ReactNode {
  // === 筛选条件 ===
  const [filterQ, setFilterQ] = useState("");
  const [filterType, setFilterType] = useState<QuestionType | "ALL">("ALL");
  const [filterDifficulty, setFilterDifficulty] = useState<
    QuestionDifficulty | "ALL"
  >("ALL");
  const [filterTextbook, setFilterTextbook] = useState("all");
  const [filterChapter, setFilterChapter] = useState("all");
  const [filterKp, setFilterKp] = useState("all");
  const [page, setPage] = useState(1);
  const pageSize = 20;

  // === 编辑弹窗状态 ===
  const [dialogOpen, setDialogOpen] = useState(false);
  const [form, setForm] = useState<QuestionFormState>(emptyForm());
  const [dialogError, setDialogError] = useState<string | null>(null);
  const [dialogSaving, setDialogSaving] = useState(false);

  // === 导入导出状态 ===
  const [importMsg, setImportMsg] = useState<string | null>(null);
  const [exportMsg, setExportMsg] = useState<string | null>(null);
  const [exportTriggered, setExportTriggered] = useState(false);
  const fileInputRef = useRef<HTMLInputElement | null>(null);

  // 当前选中教材 → 章节列表
  const dialogChapters = useMemo(() => {
    if (!form.textbookId) return [];
    const tb = MOCK_TEXTBOOK_DETAILS.find((t) => t.id === form.textbookId);
    return tb?.chapters ?? [];
  }, [form.textbookId]);

  const dialogKps = useMemo(() => {
    if (!form.chapterId) return [];
    const ch = dialogChapters.find((c) => c.id === form.chapterId);
    return ch?.knowledgePoints ?? [];
  }, [form.chapterId, dialogChapters]);

  // 筛选栏的章节列表（按筛选教材联动）
  const filterChapterOptions = useMemo(() => {
    if (filterTextbook === "all") return [];
    const tb = MOCK_TEXTBOOK_DETAILS.find((t) => t.id === filterTextbook);
    return tb?.chapters ?? [];
  }, [filterTextbook]);

  const filterKpOptions = useMemo(() => {
    if (filterChapter === "all") return [];
    const ch = filterChapterOptions.find((c) => c.id === filterChapter);
    return ch?.knowledgePoints ?? [];
  }, [filterChapter, filterChapterOptions]);

  // === GraphQL 查询 ===
  const filter: QuestionsLibraryFilter = useMemo(
    () => ({
      q: filterQ || null,
      type: filterType === "ALL" ? null : filterType,
      difficulty: filterDifficulty === "ALL" ? null : filterDifficulty,
      textbook: filterTextbook === "all" ? null : filterTextbook,
      chapter: filterChapter === "all" ? null : filterChapter,
      kp: filterKp === "all" ? null : filterKp,
      page,
      pageSize,
    }),
    [
      filterQ,
      filterType,
      filterDifficulty,
      filterTextbook,
      filterChapter,
      filterKp,
      page,
    ],
  );

  const [result] = useQuery({
    query: QuestionsLibraryQuery,
    variables: { filter },
  });

  // === Mutations ===
  const [, createQuestion] = useMutation(QuestionCreateMutation);
  const [, updateQuestion] = useMutation(QuestionUpdateMutation);
  const [, deleteQuestion] = useMutation(QuestionDeleteMutation);
  const [, batchImport] = useMutation(QuestionBatchImportMutation);
  const [exportResult, batchExport] = useQuery({
    query: QuestionBatchExportQuery,
    variables: { filter },
    pause: true, // 按需触发
  });

  const items: QuestionItem[] =
    (result.data?.questionsLibrary.items as QuestionItem[] | undefined) ?? [];
  const total = result.data?.questionsLibrary.total ?? 0;
  const totalPages = Math.max(1, Math.ceil(total / pageSize));

  // === 操作 ===
  const openCreate = useCallback(() => {
    setForm(emptyForm());
    setDialogError(null);
    setDialogOpen(true);
  }, []);

  const openEdit = useCallback((q: QuestionItem) => {
    setForm(fillForm(q));
    setDialogError(null);
    setDialogOpen(true);
  }, []);

  const handleDelete = useCallback(
    async (q: QuestionItem) => {
      if (!window.confirm(`确认删除题目 ${q.questionId}？`)) return;
      const res = await deleteQuestion({ questionId: q.questionId });
      if (res.error) {
        window.alert(`删除失败：${res.error.message}`);
      }
    },
    [deleteQuestion],
  );

  const submitForm = async () => {
    setDialogError(null);
    if (!form.content.trim()) {
      setDialogError("请填写题干");
      return;
    }
    if (!form.answer.trim()) {
      setDialogError("请填写答案");
      return;
    }
    setDialogSaving(true);
    if (form.questionId) {
      // 更新
      const input: QuestionUpdateInput = {
        questionId: form.questionId,
        content: form.content.trim(),
        type: form.type,
        difficulty: form.difficulty,
        textbookId: form.textbookId || null,
        chapterId: form.chapterId || null,
        kpId: form.kpId || null,
        score: Number(form.score) || 0,
        answer: form.answer.trim(),
        analysis: form.analysis.trim() || null,
      };
      const res = await updateQuestion({ input });
      setDialogSaving(false);
      if (res.error) {
        setDialogError(res.error.message);
        return;
      }
    } else {
      // 新建
      const input: QuestionCreateInput = {
        content: form.content.trim(),
        type: form.type,
        difficulty: form.difficulty,
        textbookId: form.textbookId || null,
        chapterId: form.chapterId || null,
        kpId: form.kpId || null,
        score: Number(form.score) || 0,
        answer: form.answer.trim(),
        analysis: form.analysis.trim() || null,
      };
      const res = await createQuestion({ input });
      setDialogSaving(false);
      if (res.error) {
        setDialogError(res.error.message);
        return;
      }
    }
    setDialogOpen(false);
  };

  // 批量导入：解析 JSON 文件
  const handleImportClick = () => {
    fileInputRef.current?.click();
  };

  const handleFileChange = async (
    e: React.ChangeEvent<HTMLInputElement>,
  ) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setImportMsg(null);
    try {
      const text = await file.text();
      const parsed = JSON.parse(text) as unknown;
      if (!Array.isArray(parsed)) {
        setImportMsg("导入失败：JSON 根节点必须是数组");
        return;
      }
      const items: QuestionBatchImportItem[] = parsed
        .filter(
          (it): it is QuestionBatchImportItem =>
            typeof it === "object" && it !== null,
        )
        .map((it) => ({
          content: String(it.content ?? ""),
          type: (it.type as QuestionType) ?? "SINGLE_CHOICE",
          difficulty: (it.difficulty as QuestionDifficulty) ?? "MEDIUM",
          textbookId: it.textbookId ?? null,
          chapterId: it.chapterId ?? null,
          kpId: it.kpId ?? null,
          score: Number(it.score) || 0,
          answer: String(it.answer ?? ""),
          analysis: it.analysis ?? null,
        }));
      if (items.length === 0) {
        setImportMsg("导入失败：未解析到有效题目");
        return;
      }
      const res = await batchImport({ input: { items } });
      if (res.error) {
        setImportMsg(`导入失败：${res.error.message}`);
        return;
      }
      const data = res.data?.questionBatchImport;
      if (data) {
        setImportMsg(
          `导入完成：成功 ${data.importedCount} 题，失败 ${data.failedCount} 题`,
        );
      }
    } catch (err) {
      setImportMsg(
        `导入失败：${err instanceof Error ? err.message : String(err)}`,
      );
    } finally {
      // 重置 input 以便重复选择同一文件
      if (fileInputRef.current) {
        fileInputRef.current.value = "";
      }
    }
  };

  // 批量导出：触发查询后由 useEffect 监听结果变化下载 JSON
  const handleExport = () => {
    setExportMsg(null);
    setExportTriggered(true);
    batchExport();
  };

  // 监听导出查询结果：数据到达后生成 Blob 下载
  useEffect(() => {
    if (!exportTriggered) return;
    const data = exportResult.data?.questionBatchExport;
    if (data) {
      const json = JSON.stringify(
        {
          exportedAt: data.exportedAt,
          count: data.items.length,
          items: data.items,
        },
        null,
        2,
      );
      const blob = new Blob([json], { type: "application/json" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `questions-export-${Date.now()}.json`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
      setExportMsg(`已导出 ${data.items.length} 题`);
      setExportTriggered(false);
    }
    if (exportResult.error) {
      setExportMsg(`导出失败：${exportResult.error.message}`);
      setExportTriggered(false);
    }
  }, [exportTriggered, exportResult.data, exportResult.error]);

  const resetFilters = () => {
    setFilterQ("");
    setFilterType("ALL");
    setFilterDifficulty("ALL");
    setFilterTextbook("all");
    setFilterChapter("all");
    setFilterKp("all");
    setPage(1);
  };

  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 QuestionsLibraryQuery · content 域（P7 扩展，MSW mock）
          </p>
        </div>
        <div className="flex items-center gap-3">
          <button
            type="button"
            onClick={handleImportClick}
            className="px-4 py-2 text-sm text-ink border border-rule rounded-button hover:bg-subtle"
          >
            批量导入
          </button>
          <input
            ref={fileInputRef}
            type="file"
            accept=".json"
            onChange={handleFileChange}
            className="hidden"
          />
          <button
            type="button"
            onClick={handleExport}
            className="px-4 py-2 text-sm text-ink border border-rule rounded-button hover:bg-subtle"
          >
            批量导出
          </button>
          <button
            type="button"
            onClick={openCreate}
            className="px-4 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover"
          >
            新建题目
          </button>
        </div>
      </header>

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

      {/* 筛选栏 */}
      <section className="mb-6">
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3">
          <input
            type="text"
            value={filterQ}
            onChange={(e) => {
              setFilterQ(e.target.value);
              setPage(1);
            }}
            placeholder="关键词（题干/知识点）"
            className="px-3 py-1.5 bg-transparent border border-rule rounded-button text-sm text-ink focus:outline-none"
          />
          <select
            value={filterType}
            onChange={(e) => {
              setFilterType(e.target.value as QuestionType | "ALL");
              setPage(1);
            }}
            className="px-2 py-1.5 bg-transparent border border-rule rounded-button text-tiny text-ink focus:outline-none"
          >
            <option value="ALL">全部类型</option>
            {QUESTION_TYPE_OPTIONS.map((o) => (
              <option key={o.value} value={o.value}>
                {o.label}
              </option>
            ))}
          </select>
          <select
            value={filterDifficulty}
            onChange={(e) => {
              setFilterDifficulty(e.target.value as QuestionDifficulty | "ALL");
              setPage(1);
            }}
            className="px-2 py-1.5 bg-transparent border border-rule rounded-button text-tiny text-ink focus:outline-none"
          >
            <option value="ALL">全部难度</option>
            {QUESTION_DIFFICULTY_OPTIONS.map((o) => (
              <option key={o.value} value={o.value}>
                {o.label}
              </option>
            ))}
          </select>
          <select
            value={filterTextbook}
            onChange={(e) => {
              setFilterTextbook(e.target.value);
              setFilterChapter("all");
              setFilterKp("all");
              setPage(1);
            }}
            className="px-2 py-1.5 bg-transparent border border-rule rounded-button text-tiny text-ink focus:outline-none"
          >
            <option value="all">全部教材</option>
            {MOCK_TEXTBOOKS.map((tb) => (
              <option key={tb.id} value={tb.id}>
                {tb.title}
              </option>
            ))}
          </select>
          <select
            value={filterChapter}
            onChange={(e) => {
              setFilterChapter(e.target.value);
              setFilterKp("all");
              setPage(1);
            }}
            disabled={filterChapterOptions.length === 0}
            className="px-2 py-1.5 bg-transparent border border-rule rounded-button text-tiny text-ink focus:outline-none disabled:opacity-50"
          >
            <option value="all">全部章节</option>
            {filterChapterOptions.map((c) => (
              <option key={c.id} value={c.id}>
                {c.title}
              </option>
            ))}
          </select>
          <select
            value={filterKp}
            onChange={(e) => {
              setFilterKp(e.target.value);
              setPage(1);
            }}
            disabled={filterKpOptions.length === 0}
            className="px-2 py-1.5 bg-transparent border border-rule rounded-button text-tiny text-ink focus:outline-none disabled:opacity-50"
          >
            <option value="all">全部知识点</option>
            {filterKpOptions.map((k) => (
              <option key={k.id} value={k.id}>
                {k.name}
              </option>
            ))}
          </select>
        </div>
        <div className="mt-3 flex items-center gap-3">
          <button
            type="button"
            onClick={resetFilters}
            className="text-tiny uppercase tracking-wide text-ink-muted hover:opacity-70"
          >
            清空筛选
          </button>
          {importMsg && <span className="text-tiny text-ink-muted">{importMsg}</span>}
          {exportMsg && <span className="text-tiny text-success">{exportMsg}</span>}
        </div>
      </section>

      {/* 数据表 */}
      {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>
      ) : items.length === 0 ? (
        <Empty
          title="暂无题目"
          description="调整筛选条件或新建题目"
          action={
            <button
              type="button"
              onClick={openCreate}
              className="px-4 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover"
            >
              新建第一道题
            </button>
          }
        />
      ) : (
        <div className="border border-rule rounded-card overflow-hidden">
          <table className="w-full text-sm">
            <thead className="bg-subtle">
              <tr className="border-b border-rule">
                <th className="text-left py-2 px-3 text-tiny uppercase tracking-wide text-ink-muted">
                  题目
                </th>
                <th className="text-left py-2 px-3 text-tiny uppercase tracking-wide text-ink-muted">
                  类型
                </th>
                <th className="text-left py-2 px-3 text-tiny uppercase tracking-wide text-ink-muted">
                  难度
                </th>
                <th className="text-left py-2 px-3 text-tiny uppercase tracking-wide text-ink-muted">
                  教材-章节
                </th>
                <th className="text-right py-2 px-3 text-tiny uppercase tracking-wide text-ink-muted">
                  分值
                </th>
                <th className="text-right py-2 px-3 text-tiny uppercase tracking-wide text-ink-muted">
                  操作
                </th>
              </tr>
            </thead>
            <tbody>
              {items.map((q) => (
                <tr
                  key={q.questionId}
                  className="border-b border-rule hover:bg-subtle"
                >
                  <td className="py-2 px-3 text-ink max-w-md">
                    <p className="line-clamp-2 whitespace-pre-line">
                      {q.content.slice(0, 100)}
                      {q.content.length > 100 ? "..." : ""}
                    </p>
                  </td>
                  <td className="py-2 px-3 text-ink-muted">
                    {TYPE_LABEL[q.type]}
                  </td>
                  <td className="py-2 px-3 text-ink-muted">
                    {DIFFICULTY_LABEL[q.difficulty]}
                  </td>
                  <td className="py-2 px-3 text-ink-muted text-tiny">
                    {q.textbookName ?? "-"}
                    <br />
                    {q.chapterName ?? "-"}
                  </td>
                  <td className="py-2 px-3 text-right font-mono text-ink">
                    {q.score}
                  </td>
                  <td className="py-2 px-3 text-right">
                    <button
                      type="button"
                      onClick={() => openEdit(q)}
                      className="text-tiny font-mono text-accent hover:opacity-70 mr-3"
                    >
                      编辑
                    </button>
                    <button
                      type="button"
                      onClick={() => handleDelete(q)}
                      className="text-tiny font-mono text-danger hover:opacity-70"
                    >
                      删除
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* 分页 */}
      {total > 0 && (
        <div className="mt-4 flex items-center justify-between text-tiny text-ink-muted">
          <span>
            第 {page} / {totalPages} 页（共 {total} 题）
          </span>
          <div className="flex gap-2">
            <button
              type="button"
              onClick={() => setPage((p) => Math.max(1, p - 1))}
              disabled={page <= 1}
              className="px-3 py-1 border border-rule rounded-button disabled:opacity-30 hover:bg-subtle"
            >
              上一页
            </button>
            <button
              type="button"
              onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
              disabled={page >= totalPages}
              className="px-3 py-1 border border-rule rounded-button disabled:opacity-30 hover:bg-subtle"
            >
              下一页
            </button>
          </div>
        </div>
      )}

      {/* 编辑/新建弹窗 */}
      {dialogOpen && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-paper/80"
          onClick={() => !dialogSaving && setDialogOpen(false)}
        >
          <div
            className="bg-paper border border-rule rounded-card p-6 w-full max-w-2xl mx-4 max-h-[90vh] overflow-y-auto"
            onClick={(e) => e.stopPropagation()}
          >
            <h2 className="text-xl font-serif text-ink mb-4">
              {form.questionId ? "编辑题目" : "新建题目"}
            </h2>
            <div className="rule-thin mb-4" />
            <div className="space-y-4">
              {/* 题干 */}
              <div>
                <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
                  题干 <span className="text-danger">*</span>
                </label>
                <textarea
                  value={form.content}
                  onChange={(e) =>
                    setForm((f) => ({ ...f, content: e.target.value }))
                  }
                  rows={4}
                  className="w-full px-3 py-2 bg-transparent border border-rule rounded-button text-sm text-ink focus:outline-none"
                  placeholder="支持换行、选项等"
                />
              </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>
                  <select
                    value={form.type}
                    onChange={(e) =>
                      setForm((f) => ({
                        ...f,
                        type: e.target.value as QuestionType,
                      }))
                    }
                    className="w-full px-3 py-2 bg-transparent border border-rule rounded-button text-sm text-ink focus:outline-none"
                  >
                    {QUESTION_TYPE_OPTIONS.map((o) => (
                      <option key={o.value} value={o.value}>
                        {o.label}
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
                    难度 <span className="text-danger">*</span>
                  </label>
                  <select
                    value={form.difficulty}
                    onChange={(e) =>
                      setForm((f) => ({
                        ...f,
                        difficulty: e.target.value as QuestionDifficulty,
                      }))
                    }
                    className="w-full px-3 py-2 bg-transparent border border-rule rounded-button text-sm text-ink focus:outline-none"
                  >
                    {QUESTION_DIFFICULTY_OPTIONS.map((o) => (
                      <option key={o.value} value={o.value}>
                        {o.label}
                      </option>
                    ))}
                  </select>
                </div>
              </div>
              {/* 教材 / 章节 / 知识点 */}
              <div className="grid grid-cols-3 gap-4">
                <div>
                  <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
                    教材
                  </label>
                  <select
                    value={form.textbookId}
                    onChange={(e) =>
                      setForm((f) => ({
                        ...f,
                        textbookId: e.target.value,
                        chapterId: "",
                        kpId: "",
                      }))
                    }
                    className="w-full px-3 py-2 bg-transparent border border-rule rounded-button text-tiny text-ink focus:outline-none"
                  >
                    <option value="">不关联</option>
                    {MOCK_TEXTBOOKS.map((tb) => (
                      <option key={tb.id} value={tb.id}>
                        {tb.title}
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
                    章节
                  </label>
                  <select
                    value={form.chapterId}
                    onChange={(e) =>
                      setForm((f) => ({
                        ...f,
                        chapterId: e.target.value,
                        kpId: "",
                      }))
                    }
                    disabled={dialogChapters.length === 0}
                    className="w-full px-3 py-2 bg-transparent border border-rule rounded-button text-tiny text-ink focus:outline-none disabled:opacity-50"
                  >
                    <option value="">不关联</option>
                    {dialogChapters.map((c) => (
                      <option key={c.id} value={c.id}>
                        {c.title}
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
                    知识点
                  </label>
                  <select
                    value={form.kpId}
                    onChange={(e) =>
                      setForm((f) => ({ ...f, kpId: e.target.value }))
                    }
                    disabled={dialogKps.length === 0}
                    className="w-full px-3 py-2 bg-transparent border border-rule rounded-button text-tiny text-ink focus:outline-none disabled:opacity-50"
                  >
                    <option value="">不关联</option>
                    {dialogKps.map((k) => (
                      <option key={k.id} value={k.id}>
                        {k.name}
                      </option>
                    ))}
                  </select>
                </div>
              </div>
              {/* 分值 */}
              <div className="w-32">
                <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
                  分值 <span className="text-danger">*</span>
                </label>
                <input
                  type="number"
                  min={0}
                  value={form.score}
                  onChange={(e) =>
                    setForm((f) => ({ ...f, score: e.target.value }))
                  }
                  className="w-full px-3 py-2 bg-transparent border border-rule rounded-button text-sm text-ink font-mono focus:outline-none"
                />
              </div>
              {/* 答案 */}
              <div>
                <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
                  答案 <span className="text-danger">*</span>
                </label>
                <textarea
                  value={form.answer}
                  onChange={(e) =>
                    setForm((f) => ({ ...f, answer: 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>
              {/* 解析 */}
              <div>
                <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
                  解析
                </label>
                <textarea
                  value={form.analysis}
                  onChange={(e) =>
                    setForm((f) => ({ ...f, analysis: 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>
              {/* 错误提示 */}
              {dialogError && (
                <div className="mark-left py-2 border-l-2 border-danger pl-md">
                  <p className="text-sm px-3 text-danger">{dialogError}</p>
                </div>
              )}
              {/* 操作按钮 */}
              <div className="flex items-center gap-3 pt-2">
                <button
                  type="button"
                  onClick={submitForm}
                  disabled={dialogSaving}
                  className="px-4 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover disabled:opacity-50"
                >
                  {dialogSaving
                    ? "保存中..."
                    : form.questionId
                      ? "保存修改"
                      : "创建题目"}
                </button>
                <button
                  type="button"
                  onClick={() => setDialogOpen(false)}
                  disabled={dialogSaving}
                  className="text-tiny uppercase tracking-wide text-ink-muted hover:opacity-70"
                >
                  取消
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      <p className="mt-8 text-tiny text-ink-muted">
        <Link
          href="/dashboard"
          className="text-tiny uppercase tracking-wide text-ink-muted hover:opacity-70"
        >
          ← 返回仪表盘
        </Link>
      </p>
    </div>
  );
}
