"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import { get, post } from "@/lib/api";

type KillSwitchState = { active: boolean; reason: string | null; tripped_at: string | null };

/**
 * Global kill-switch, surfaced in the app header so it is always reachable. Shows
 * the current state (AI active / paused) and opens a small popover to pause all AI
 * work (trip, with an optional reason) or resume it (reset). It polls so the state
 * stays current if another admin flips it.
 */
export default function KillSwitch() {
  const [state, setState] = useState<KillSwitchState | null>(null);
  const [open, setOpen] = useState(false);
  const [busy, setBusy] = useState(false);
  const [reason, setReason] = useState("");
  const ref = useRef<HTMLDivElement>(null);

  const load = useCallback(async () => {
    try {
      const d = await get<{ killSwitch: KillSwitchState }>("kill-switch");
      setState(d.killSwitch);
    } catch {
      /* keep last known state on a transient error */
    }
  }, []);

  useEffect(() => {
    load();
    const t = setInterval(load, 30_000);
    return () => clearInterval(t);
  }, [load]);

  // Close the popover on outside click / Escape.
  useEffect(() => {
    if (!open) return;
    const onDown = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setOpen(false);
    };
    document.addEventListener("mousedown", onDown);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("mousedown", onDown);
      document.removeEventListener("keydown", onKey);
    };
  }, [open]);

  async function trip() {
    setBusy(true);
    try {
      await post("kill-switch/trip", { reason: reason.trim() || "Paused from the header." });
      setReason("");
      await load();
      setOpen(false);
    } finally {
      setBusy(false);
    }
  }

  async function reset() {
    setBusy(true);
    try {
      await post("kill-switch/reset");
      await load();
      setOpen(false);
    } finally {
      setBusy(false);
    }
  }

  if (!state) return null;
  const active = state.active;

  return (
    <div className="relative" ref={ref}>
      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        aria-haspopup="dialog"
        aria-expanded={open}
        title={active ? "AI processing paused (kill-switch active)" : "AI processing active — click to pause"}
        className={`flex items-center gap-2 rounded-md border px-2.5 py-1.5 text-sm font-medium transition-colors ${
          active ? "border-red-300 bg-red-50 text-danger" : "border-slate-200 text-slate-600 hover:bg-slate-100"
        }`}
      >
        <span className={`inline-block h-2 w-2 rounded-full ${active ? "animate-pulse bg-danger" : "bg-ok"}`} />
        <span className="hidden sm:inline">{active ? "AI paused" : "AI active"}</span>
      </button>

      {open && (
        <div
          role="dialog"
          aria-label="Global kill-switch"
          className="absolute right-0 z-50 mt-2 w-72 rounded-lg border border-slate-200 bg-white p-3 shadow-lg"
        >
          <h3 className="flex items-center gap-2 text-sm font-semibold text-slate-900">
            Global kill-switch
            <span className={`rounded-sm px-1.5 py-0.5 text-xs font-medium ${active ? "bg-red-100 text-danger" : "bg-emerald-100 text-emerald-700"}`}>
              {active ? "paused" : "running"}
            </span>
          </h3>
          <p className="mt-1 text-xs text-slate-500">
            {active
              ? "All new AI work is halted; products already in flight finish."
              : "Halts all new AI work immediately; products already in flight finish."}
          </p>
          {active && state.reason && (
            <p className="mt-2 rounded-sm bg-slate-50 px-2 py-1 text-xs text-slate-600">Reason: {state.reason}</p>
          )}
          {active ? (
            <button type="button" className="btn-primary mt-3 w-full" onClick={reset} disabled={busy}>
              {busy ? "Resuming…" : "Resume AI processing"}
            </button>
          ) : (
            <div className="mt-3 space-y-2">
              <input
                value={reason}
                onChange={(e) => setReason(e.target.value)}
                placeholder="Reason (optional)"
                className="input text-sm"
              />
              <button type="button" className="btn-danger w-full" onClick={trip} disabled={busy}>
                {busy ? "Pausing…" : "Pause all AI"}
              </button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
