"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";

export function UnpublishRecipeButton({ recipeId }: { recipeId: string }) {
  const router = useRouter();
  const [busy, setBusy] = useState(false);

  async function unpublish() {
    if (!confirm("Unpublish this recipe? It becomes private — only the author can see it.")) return;
    setBusy(true);
    try {
      const res = await fetch(`/api/v1/admin/recipes/${recipeId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "unpublish" }),
      });
      if (!res.ok) throw new Error();
      toast.success("Recipe unpublished");
      router.refresh();
    } catch {
      toast.error("Failed to unpublish");
    } finally {
      setBusy(false);
    }
  }

  return (
    <Button type="button" variant="outline" size="sm" className="h-6 px-2 text-xs" disabled={busy} onClick={() => { void unpublish(); }}>
      {busy ? "Unpublishing…" : "Unpublish"}
    </Button>
  );
}
