"use client";

import { useRef, useState } from "react";
import { useFormStatus } from "react-dom";
import ConfirmDialog from "@/components/ui/ConfirmDialog";
import { deleteAllNotifications } from "./actions";

/**
 * Same intercept-then-`requestSubmit` trick as the delete-selected button. The
 * submitter carries its own `formAction`, so re-submitting through it targets
 * the delete-all action rather than the form's default.
 */
export default function DeleteAllButton() {
  const { pending } = useFormStatus();
  const btnRef = useRef<HTMLButtonElement>(null);
  const [open, setOpen] = useState(false);

  return (
    <>
      <button
        ref={btnRef}
        type="submit"
        formAction={deleteAllNotifications}
        onClick={(e) => {
          e.preventDefault();
          setOpen(true);
        }}
        disabled={pending}
        className="rounded-lg border border-[#CC1414] bg-white px-3 py-1.5 text-sm font-medium text-[#CC1414] hover:bg-[#CC1414]/5 disabled:opacity-50"
      >
        Delete all
      </button>

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