"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Ban, Play, Trash2, Loader2, ArrowUpCircle } from "lucide-react";

type Action = "suspend" | "activate" | "delete" | "promote";

export function TenantActions({
  tenantId,
  isActive,
  isAdmin,
  name,
  hasPooled = false,
}: {
  tenantId: number;
  isActive: boolean;
  isAdmin: boolean;
  name: string;
  hasPooled?: boolean;
}) {
  const router = useRouter();
  const [busy, setBusy] = useState<Action | null>(null);
  const [error, setError] = useState("");
  const [info, setInfo] = useState("");

  if (isAdmin) return <span className="text-xs text-slate-400">—</span>;

  async function run(action: Action) {
    if (action === "delete" && !confirm(`Delete tenant "${name}" and all their agents/containers? This cannot be undone.`)) return;
    if (action === "suspend" && !confirm(`Suspend "${name}"? They won't be able to log in and their containers will be stopped.`)) return;
    if (action === "promote" && !confirm(`Move "${name}"'s pooled employees into their own dedicated container?`)) return;
    setBusy(action);
    setError("");
    setInfo("");
    const res = await fetch(`/api/admin/tenants/${tenantId}`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ action }),
    });
    setBusy(null);
    if (!res.ok) {
      const b = await res.json().catch(() => ({}));
      setError(b.error || "Failed.");
      return;
    }
    if (action === "promote") setInfo("Migration queued — takes a few minutes.");
    router.refresh();
  }

  return (
    <div className="flex flex-col items-start gap-1">
      <div className="flex gap-1.5">
        {isActive ? (
          <button
            onClick={() => run("suspend")}
            disabled={!!busy}
            className="inline-flex items-center gap-1 rounded-md border border-amber-300 px-2 py-1 text-xs font-medium text-amber-700 hover:bg-amber-50 disabled:opacity-50"
            title="Suspend"
          >
            {busy === "suspend" ? <Loader2 size={13} className="animate-spin" /> : <Ban size={13} />}
            Suspend
          </button>
        ) : (
          <button
            onClick={() => run("activate")}
            disabled={!!busy}
            className="inline-flex items-center gap-1 rounded-md border border-emerald-300 px-2 py-1 text-xs font-medium text-emerald-700 hover:bg-emerald-50 disabled:opacity-50"
            title="Reactivate"
          >
            {busy === "activate" ? <Loader2 size={13} className="animate-spin" /> : <Play size={13} />}
            Reactivate
          </button>
        )}
        {hasPooled && (
          <button
            onClick={() => run("promote")}
            disabled={!!busy}
            className="inline-flex items-center gap-1 rounded-md border border-cyan-300 px-2 py-1 text-xs font-medium text-cyan-700 hover:bg-cyan-50 disabled:opacity-50"
            title="Move pooled employees to a dedicated company container"
          >
            {busy === "promote" ? <Loader2 size={13} className="animate-spin" /> : <ArrowUpCircle size={13} />}
            Dedicate
          </button>
        )}
        <button
          onClick={() => run("delete")}
          disabled={!!busy}
          className="inline-flex items-center gap-1 rounded-md border border-red-300 px-2 py-1 text-xs font-medium text-red-600 hover:bg-red-50 disabled:opacity-50"
          title="Delete"
        >
          {busy === "delete" ? <Loader2 size={13} className="animate-spin" /> : <Trash2 size={13} />}
          Delete
        </button>
      </div>
      {error && <span className="text-[11px] text-red-600">{error}</span>}
      {info && <span className="text-[11px] text-cyan-700">{info}</span>}
    </div>
  );
}
