"use client";

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

/**
 * The selection itself is plain HTML — checked checkboxes named `id` inside the
 * surrounding form — so nothing here owns the list. This component only needs
 * the *count*, for the label and the confirmation copy, which it reads back off
 * the DOM instead of duplicating the selection in a `Set`.
 *
 * The click is intercepted to show the same ConfirmDialog as before; confirming
 * re-submits through `requestSubmit`, so the server action runs exactly as if
 * the user had pressed the button directly.
 */
export default function DeleteSelectedButton() {
  const { pending } = useFormStatus();
  const btnRef = useRef<HTMLButtonElement>(null);
  const [count, setCount] = useState(0);
  const [open, setOpen] = useState(false);

  useEffect(() => {
    const form = btnRef.current?.form;
    if (!form) return;
    const sync = () =>
      setCount(form.querySelectorAll<HTMLInputElement>('input[name="id"]:checked').length);
    sync();
    form.addEventListener("change", sync);
    return () => form.removeEventListener("change", sync);
  }, []);

  return (
    <>
      <button
        ref={btnRef}
        type="submit"
        onClick={(e) => {
          e.preventDefault();
          setOpen(true);
        }}
        disabled={pending || count === 0}
        className="rounded-lg border border-gray-200 px-3 py-1.5 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50"
      >
        Delete selected ({count})
      </button>

      <ConfirmDialog
        open={open}
        title="Delete selected notifications?"
        description={`This will permanently delete ${count} selected notification${count === 1 ? "" : "s"}.`}
        confirmLabel="Delete"
        loading={pending}
        onCancel={() => setOpen(false)}
        onConfirm={() => {
          setOpen(false);
          const btn = btnRef.current;
          btn?.form?.requestSubmit(btn);
        }}
      />
    </>
  );
}
