import { useEffect, useMemo, useState } from "react";
import {
  listPrompts,
  groupPrompts,
  createPromptVersion,
  activatePrompt,
  deactivatePrompt,
  type PromptGroup,
} from "../api";
import { lineDiff, diffStat } from "../lib/diff";

// 受管 prompt key 的中文别名（仅展示用；key 本身是事实源）。
const KEY_LABELS: Record<string, string> = {
  "graph.extract": "知识图谱抽取",
  "eval.quality": "评测 · 质量打分",
  "eval.refine": "评测 · 纠偏重写",
  "guard.jailbreak": "安全 · 越狱检测",
  "coordinator.lead": "多智能体 · 主协调",
  "memory.extract": "记忆 · 偏好抽取",
};

export function PromptsPage() {
  const [groups, setGroups] = useState<PromptGroup[]>([]);
  const [sel, setSel] = useState<string>(""); // 当前选中的 key
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState("");

  // 新建版本编辑态
  const [draft, setDraft] = useState("");
  const [note, setNote] = useState("");
  const [busy, setBusy] = useState(false);
  const [msg, setMsg] = useState("");

  // 选某版做 diff（against 当前激活版）；null=不展开
  const [diffVer, setDiffVer] = useState<number | null>(null);

  const load = async () => {
    setLoading(true);
    setErr("");
    try {
      const gs = groupPrompts(await listPrompts());
      setGroups(gs);
      setSel((s) => (s && gs.some((g) => g.key === s) ? s : gs[0]?.key ?? ""));
    } catch (e) {
      setErr((e as Error).message);
    } finally {
      setLoading(false);
    }
  };
  useEffect(() => {
    void load();
  }, []);

  const cur = useMemo(() => groups.find((g) => g.key === sel) ?? null, [groups, sel]);

  // 选 key 时重置编辑/diff 态。
  const pick = (key: string) => {
    setSel(key);
    setDraft("");
    setNote("");
    setMsg("");
    setDiffVer(null);
  };

  const submitVersion = async () => {
    if (!cur || !draft.trim()) return;
    setBusy(true);
    setMsg("");
    try {
      const v = await createPromptVersion(cur.key, draft, note);
      setMsg(`✓ 已建版本 v${v}（未激活）`);
      setDraft("");
      setNote("");
      await load();
    } catch (e) {
      setMsg((e as Error).message);
    } finally {
      setBusy(false);
    }
  };

  const activate = async (version: number) => {
    if (!cur) return;
    setBusy(true);
    setMsg("");
    try {
      await activatePrompt(cur.key, version);
      setMsg(`✓ v${version} 已激活并热下发各服务`);
      await load();
    } catch (e) {
      setMsg((e as Error).message);
    } finally {
      setBusy(false);
    }
  };

  const deactivate = async () => {
    if (!cur) return;
    setBusy(true);
    setMsg("");
    try {
      await deactivatePrompt(cur.key);
      setMsg("✓ 已撤销激活，回退代码内置默认（热）");
      await load();
    } catch (e) {
      setMsg((e as Error).message);
    } finally {
      setBusy(false);
    }
  };

  if (loading) return <div className="text-sm text-gray-400">加载中…</div>;
  if (err) return <div className="text-sm text-rose-600">{err}</div>;

  return (
    <div className="grid grid-cols-1 gap-6 lg:grid-cols-[260px_1fr]">
      {/* 左：受管 key 列表 */}
      <section className="rounded-xl border border-gray-100 bg-white p-3 shadow-sm h-fit">
        <h3 className="px-2 py-1 text-xs font-semibold text-gray-400">受管提示词（{groups.length}）</h3>
        <ul className="mt-1 space-y-0.5">
          {groups.map((g) => (
            <li key={g.key}>
              <button
                onClick={() => pick(g.key)}
                className={`w-full rounded-lg px-2.5 py-2 text-left transition ${
                  g.key === sel ? "bg-violet-50 ring-1 ring-violet-200" : "hover:bg-gray-50"
                }`}
              >
                <div className="text-xs font-semibold text-gray-700">{KEY_LABELS[g.key] ?? g.key}</div>
                <div className="mt-0.5 flex items-center gap-1.5">
                  <code className="text-[10px] text-gray-400">{g.key}</code>
                  {g.active ? (
                    <span className="rounded bg-emerald-50 px-1.5 text-[9px] font-semibold text-emerald-600">
                      v{g.active.version} 激活
                    </span>
                  ) : (
                    <span className="rounded bg-gray-100 px-1.5 text-[9px] text-gray-400">默认</span>
                  )}
                </div>
              </button>
            </li>
          ))}
        </ul>
      </section>

      {/* 右：选中 key 的版本与编辑 */}
      {cur && (
        <div className="space-y-6">
          {/* 当前状态 + 撤销 */}
          <section className="rounded-xl border border-gray-100 bg-white p-5 shadow-sm">
            <div className="flex items-start justify-between">
              <div>
                <h3 className="text-sm font-semibold text-gray-800">{KEY_LABELS[cur.key] ?? cur.key}</h3>
                <code className="text-[11px] text-gray-400">{cur.key}</code>
              </div>
              <div className="text-right">
                {cur.active ? (
                  <>
                    <span className="rounded bg-emerald-50 px-2 py-0.5 text-xs font-semibold text-emerald-600">
                      当前激活 v{cur.active.version}
                    </span>
                    <button
                      onClick={deactivate}
                      disabled={busy}
                      className="ml-2 rounded border border-gray-200 px-2.5 py-0.5 text-xs text-gray-500 hover:bg-gray-50 disabled:opacity-40"
                    >
                      撤销 → 回默认
                    </button>
                  </>
                ) : (
                  <span className="rounded bg-gray-100 px-2 py-0.5 text-xs text-gray-500">使用代码内置默认</span>
                )}
              </div>
            </div>
            {msg && (
              <div className={`mt-3 text-xs ${msg.startsWith("✓") ? "text-emerald-600" : "text-rose-600"}`}>{msg}</div>
            )}
          </section>

          {/* 版本列表 */}
          <section className="rounded-xl border border-gray-100 bg-white p-5 shadow-sm">
            <h3 className="mb-3 text-sm font-semibold text-gray-700">版本历史（{cur.versions.length}）</h3>
            {cur.versions.length === 0 ? (
              <div className="text-xs text-gray-400">还没有自定义版本，下方可建第一版。</div>
            ) : (
              <ul className="space-y-2">
                {cur.versions.map((v) => {
                  const isActive = v.active;
                  const showDiff = diffVer === v.version && cur.active != null && cur.active.version !== v.version;
                  return (
                    <li key={v.version} className="rounded-lg border border-gray-100 p-3">
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-2">
                          <span className="font-mono text-xs font-semibold text-gray-700">v{v.version}</span>
                          {isActive && (
                            <span className="rounded bg-emerald-50 px-1.5 text-[10px] font-semibold text-emerald-600">激活中</span>
                          )}
                          {v.note && <span className="text-[11px] text-gray-400">{v.note}</span>}
                        </div>
                        <div className="flex items-center gap-1.5">
                          {cur.active && cur.active.version !== v.version && (
                            <button
                              onClick={() => setDiffVer(showDiff ? null : v.version)}
                              className="rounded border border-gray-200 px-2 py-0.5 text-[11px] text-gray-500 hover:bg-gray-50"
                            >
                              {showDiff ? "收起对比" : "对比激活版"}
                            </button>
                          )}
                          {!isActive && (
                            <button
                              onClick={() => activate(v.version)}
                              disabled={busy}
                              className="rounded bg-violet-600 px-2.5 py-0.5 text-[11px] text-white hover:bg-violet-700 disabled:opacity-40"
                            >
                              激活
                            </button>
                          )}
                        </div>
                      </div>
                      {/* 正文 / diff */}
                      {showDiff && cur.active ? (
                        <DiffView from={cur.active.content} to={v.content} />
                      ) : (
                        <pre className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap rounded bg-gray-50 p-2 text-[11px] leading-relaxed text-gray-600">
                          {v.content}
                        </pre>
                      )}
                    </li>
                  );
                })}
              </ul>
            )}
          </section>

          {/* 新建版本 */}
          <section className="rounded-xl border border-gray-100 bg-white p-5 shadow-sm">
            <h3 className="mb-1 text-sm font-semibold text-gray-700">建新版本</h3>
            <p className="mb-3 text-[11px] text-gray-400">新版本保存后默认不激活，确认无误再点「激活」热下发各服务。</p>
            <textarea
              value={draft}
              onChange={(e) => setDraft(e.target.value)}
              rows={6}
              placeholder="提示词正文…"
              className="w-full rounded border px-3 py-2 text-xs leading-relaxed focus:border-violet-500 focus:outline-none"
            />
            <div className="mt-2 flex items-center gap-2">
              <input
                value={note}
                onChange={(e) => setNote(e.target.value)}
                placeholder="版本说明（可选，如：收紧越狱判定）"
                className="flex-1 rounded border px-3 py-1.5 text-xs focus:border-violet-500 focus:outline-none"
              />
              <button
                onClick={submitVersion}
                disabled={busy || !draft.trim()}
                className="rounded bg-violet-600 px-4 py-1.5 text-xs text-white hover:bg-violet-700 disabled:opacity-40"
              >
                {busy ? "保存中…" : "保存为新版本"}
              </button>
            </div>
          </section>
        </div>
      )}
    </div>
  );
}

// DiffView：行级差异（激活版 → 该版）。
function DiffView({ from, to }: { from: string; to: string }) {
  const lines = lineDiff(from, to);
  const stat = diffStat(lines);
  return (
    <div className="mt-2 overflow-auto rounded bg-gray-50 p-2 text-[11px] leading-relaxed">
      <div className="mb-1 font-mono text-[10px] text-gray-400">
        对比激活版　<span className="text-emerald-600">+{stat.add}</span> <span className="text-rose-600">-{stat.del}</span>
      </div>
      <pre className="whitespace-pre-wrap">
        {lines.map((l, i) => (
          <div
            key={i}
            className={
              l.op === "add"
                ? "bg-emerald-50 text-emerald-700"
                : l.op === "del"
                  ? "bg-rose-50 text-rose-700"
                  : "text-gray-500"
            }
          >
            <span className="select-none text-gray-300">{l.op === "add" ? "+ " : l.op === "del" ? "- " : "  "}</span>
            {l.text}
          </div>
        ))}
      </pre>
    </div>
  );
}
