"use client";
import { useRouter } from "next/navigation";
import { useSession } from "next-auth/react";
import { useState } from "react";

export default function DeleteButton({ url, label = "Delete" }: { url: string; label?: string }) {
  const router = useRouter();
  const { data: session } = useSession();
  const [loading, setLoading] = useState(false);

  // permissions is null for the primary admin (full access) or for
  // sessions where it hasn't loaded yet — only hide the button once we
  // positively know this staff account lacks the "delete" permission.
  const permissionsRaw = (session?.user as any)?.permissions;
  if (permissionsRaw) {
    try {
      const perms: string[] = JSON.parse(permissionsRaw);
      if (!perms.includes("delete")) return null;
    } catch {}
  }

  async function handleDelete() {
    if (!confirm("Are you sure you want to delete this? This cannot be undone.")) return;
    setLoading(true);
    const res = await fetch(url, { method: "DELETE" });
    if (!res.ok) {
      const data = await res.json().catch(() => ({}));
      alert(data.error || "You don't have permission to delete this.");
      setLoading(false);
      return;
    }
    router.refresh();
  }

  return (
    <button onClick={handleDelete} disabled={loading} className="text-neutral-500 hover:text-red-500">
      {loading ? "..." : label}
    </button>
  );
}
