// 全局治理：CONVENTIONS 规则来源 + 应用梦核建议（写入 master 并同步所有项目）
// 2026-07-02 ui-restructure N3：从单项目 GovernancePanel 迁出——这两块操作影响所有项目，属全局层
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import {
  getUserConventionsStatus,
  saveUserConventions,
  resetConventionsToBuiltin,
  type UserConventionsStatus,
} from "../../lib/commands";

export function GlobalGovernancePanel() {
  const { data: userConventions, refetch: refetchUserConventions } = useQuery<UserConventionsStatus>({
    queryKey: ["user-conventions-status"],
    queryFn: () => getUserConventionsStatus(),
  });

  const [conventionsInput, setConventionsInput] = useState("");
  const [editorOpen, setEditorOpen] = useState(false);
  const [saving, setSaving] = useState(false);
  const [saveResult, setSaveResult] = useState<string | null>(null);
  const [saveError, setSaveError] = useState<string | null>(null);

  const handleSave = async () => {
    if (!conventionsInput.trim()) return;
    setSaving(true);
    setSaveError(null);
    setSaveResult(null);
    try {
      const res = await saveUserConventions(conventionsInput);
      setSaveResult(`已应用 v${res.version}，同步了 ${res.synced_count} 个项目`);
      setConventionsInput("");
      setEditorOpen(false);
      refetchUserConventions();
    } catch (e) {
      setSaveError(String(e));
    } finally {
      setSaving(false);
    }
  };

  const handleReset = async () => {
    setSaving(true);
    setSaveError(null);
    setSaveResult(null);
    try {
      const res = await resetConventionsToBuiltin();
      setSaveResult(`已重置为内置基线 v${res.version}，同步了 ${res.synced_count} 个项目`);
      refetchUserConventions();
    } catch (e) {
      setSaveError(String(e));
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="p-4 space-y-4 max-w-2xl">
      <div>
        <h3 className="text-sm font-semibold text-gray-800">全局治理</h3>
        <p className="text-[10px] text-gray-400 mt-0.5">CONVENTIONS 规则库——此处的变更同步到所有已接入项目</p>
      </div>

      {/* 规则来源 */}
      {userConventions && (
        <div className="flex items-center justify-between bg-gray-50 rounded-lg px-3 py-2">
          <span className="text-[11px] text-gray-500">规则来源</span>
          {userConventions.source === "user" ? (
            <span className="text-[11px] font-mono text-purple-600 bg-purple-50 px-2 py-0.5 rounded">
              用户自定义 v{userConventions.version}
              {userConventions.outdated_from_builtin && (
                <span className="ml-1 text-yellow-600">⚠️ 低于内置</span>
              )}
            </span>
          ) : (
            <span className="text-[11px] font-mono text-gray-500 bg-white border border-gray-200 px-2 py-0.5 rounded">
              内置基线 v{userConventions.builtin_version}
            </span>
          )}
        </div>
      )}

      {/* 应用梦核建议 */}
      <div className="bg-white rounded-lg border border-gray-100 p-3 space-y-2">
        <div className="flex items-center justify-between">
          <p className="text-[10px] font-semibold text-gray-400 uppercase tracking-wider">应用梦核建议</p>
          <button
            onClick={() => { setEditorOpen((v) => !v); setSaveError(null); }}
            className="text-[11px] text-blue-500 hover:text-blue-600"
          >
            {editorOpen ? "收起" : "展开"}
          </button>
        </div>
        {editorOpen && (
          <div className="space-y-2">
            <p className="text-[11px] text-gray-500 leading-relaxed">
              将梦核 Opus 输出的新 CONVENTIONS 内容粘贴到下方，确认后将写入并同步所有项目。
            </p>
            <textarea
              value={conventionsInput}
              onChange={(e) => setConventionsInput(e.target.value)}
              placeholder="粘贴完整的 CONVENTIONS.md 内容（须包含 frontmatter version 字段）…"
              rows={8}
              className="w-full text-[11px] font-mono border border-gray-200 rounded p-2 resize-none focus:outline-none focus:border-blue-400"
            />
            {saveError && (
              <p className="text-[11px] text-red-600 font-mono break-all">{saveError}</p>
            )}
            <div className="flex gap-2">
              <button
                onClick={handleSave}
                disabled={saving || !conventionsInput.trim()}
                className="flex-1 py-1.5 rounded-lg bg-blue-500 text-white text-xs hover:bg-blue-600 disabled:opacity-50 transition-colors"
              >
                {saving ? "写入中…" : "确认应用"}
              </button>
              {userConventions?.source === "user" && (
                <button
                  onClick={handleReset}
                  disabled={saving}
                  className="px-3 py-1.5 rounded-lg border border-gray-200 text-gray-600 text-xs hover:bg-gray-50 disabled:opacity-50 transition-colors"
                >
                  重置为基线
                </button>
              )}
            </div>
          </div>
        )}
        {!editorOpen && userConventions?.source === "user" && (
          <div className="flex items-center justify-between">
            <p className="text-[11px] text-gray-500">当前使用用户自定义规则</p>
            <button
              onClick={handleReset}
              disabled={saving}
              className="text-[11px] text-gray-400 hover:text-red-500 disabled:opacity-50 transition-colors"
            >
              重置为基线
            </button>
          </div>
        )}
        {saveResult && (
          <p className="text-[11px] text-green-600 bg-green-50 rounded px-2 py-1">✓ {saveResult}</p>
        )}
      </div>

      <p className="text-[10px] text-gray-300 leading-relaxed">
        项目级操作（同步规则到某项目、接入包、蓝图提示词）在各项目蓝图 → ⚙️ 治理面板中进行。
      </p>
    </div>
  );
}
