"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";

type Props = {
  enabled: boolean;
  updatedAt?: string | null;
};

export function MasterAgentTakeoverClient({ enabled, updatedAt }: Props) {
  const router = useRouter();
  const [takeoverEnabled, setTakeoverEnabled] = useState(enabled);
  const [busy, setBusy] = useState(false);
  const [message, setMessage] = useState("");

  async function save() {
    setBusy(true);
    setMessage("");

    const response = await fetch("/api/v1/projects/master-agent/agent-controls", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ globalTakeoverEnabled: takeoverEnabled }),
    });
    const result = (await response.json()) as { ok: boolean; message?: string };

    setBusy(false);
    setMessage(
      result.ok
        ? takeoverEnabled
          ? "已开启全局主 Agent 协同接管。"
          : "已关闭全局主 Agent 协同接管。"
        : result.message ?? "保存失败。",
    );

    if (result.ok) {
      router.refresh();
    }
  }

  return (
    <div className="flex flex-col gap-4 px-[18px] pb-6">
      <div className="rounded-2xl border border-[#E5E5EA] bg-white px-4 py-4">
        <div className="flex items-start justify-between gap-4">
          <div className="space-y-2">
            <div className="text-[16px] font-semibold text-[#111111]">全局主 Agent 协同接管</div>
            <div className="text-[12px] leading-6 text-[#8C8C8C]">
              这是全局默认开关。开启后，新线程默认允许主 Agent 协同推进，但不会抢走你继续直接控制线程开发的能力。
            </div>
            <div className="text-[12px] leading-6 text-[#8C8C8C]">
              某个线程如果单独关闭了协同接管，会优先按线程自己的开关处理。
            </div>
          </div>
          <label className="inline-flex shrink-0 items-center gap-2 rounded-full bg-[#F7F8FA] px-3 py-2 text-[13px] font-semibold text-[#111111]">
            <input
              type="checkbox"
              checked={takeoverEnabled}
              onChange={(event) => setTakeoverEnabled(event.target.checked)}
              className="h-4 w-4 accent-[#07C160]"
            />
            开启
          </label>
        </div>
        <div className="mt-4 flex flex-wrap items-center gap-3">
          <button
            type="button"
            onClick={() => void save()}
            disabled={busy}
            className="rounded-full bg-[#07C160] px-4 py-2 text-[13px] font-semibold text-white disabled:opacity-60"
          >
            {busy ? "保存中" : "保存全局接管"}
          </button>
          {updatedAt ? <span className="text-[12px] text-[#8C8C8C]">最近更新：{updatedAt}</span> : null}
        </div>
      </div>
      {message ? (
        <div className="rounded-2xl border border-[#E5E5EA] bg-white px-4 py-3 text-[13px] text-[#57606A]">
          {message}
        </div>
      ) : null}
    </div>
  );
}
