"use client";

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

export default function AdminShopToggle({ shopId, open }: { shopId: string; open: boolean }) {
  const router = useRouter();
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function toggle() {
    if (open && !confirm("Close this shop? Buyers won't see its products.")) return;
    setBusy(true);
    setError(null);
    const res = await fetch("/api/admin/merch/shops", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ shopId, open: !open }),
    }).catch(() => null);
    const data = res ? await res.json().catch(() => ({})) : {};
    setBusy(false);
    if (!res || !res.ok) {
      setError(data.error || "Failed");
      return;
    }
    router.refresh();
  }

  return (
    <span className="inline-flex flex-col items-end gap-1">
      <button type="button" onClick={toggle} disabled={busy} className={`be-act ${open ? "be-act-ghost" : "be-act-ok"}`}>
        {busy ? "…" : open ? "Close shop" : "Open shop"}
      </button>
      {error && <span className="text-xs text-[color:var(--pill-danger-fg)]">{error}</span>}
    </span>
  );
}
