"use client";

import { useRef, useState } from "react";
import { useFormStatus } from "react-dom";
import { Trash2 } from "lucide-react";
import ConfirmDialog from "@/components/ui/ConfirmDialog";

/**
 * Client only for the confirmation step: the dialog needs `open` state and
 * `useFormStatus` needs an enclosing form. Confirming re-submits that form via
 * `requestSubmit`, so the server action — and its redirect — behave exactly as
 * if the button had been pressed directly.
 */
export default function DeleteStaffButton({ name }: { name: string }) {
  const { pending } = useFormStatus();
  const btnRef = useRef<HTMLButtonElement>(null);
  const [open, setOpen] = useState(false);

  return (
    <>
      <button
        ref={btnRef}
        type="submit"
        onClick={(e) => {
          e.preventDefault();
          setOpen(true);
        }}
        disabled={pending}
        className="inline-flex items-center gap-1 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm font-medium text-red-700 hover:bg-red-100 disabled:opacity-60"
      >
        <Trash2 className="h-4 w-4" /> Delete
      </button>

      <ConfirmDialog
        open={open}
        title="Delete staff member?"
        description={`This will permanently remove "${name}". This action cannot be undone.`}
        confirmLabel="Delete"
        loading={pending}
        onCancel={() => setOpen(false)}
        onConfirm={() => {
          setOpen(false);
          const btn = btnRef.current;
          btn?.form?.requestSubmit(btn);
        }}
      />
    </>
  );
}
