import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@repo/shadcn-ui/components";
import { useRef } from "react";

interface CustomDialogProps {
  open: boolean;
  onConfirm: (ok: boolean) => void;
  title?: string;
  description?: string;
  cancelLabel?: string;
  confirmLabel?: string;
}

export const CustomDialog = ({
  open,
  onConfirm,
  title,
  description,
  cancelLabel,
  confirmLabel,
}: CustomDialogProps) => {
  const closedByActionRef = useRef(false);

  const handleClose = (ok: boolean) => {
    closedByActionRef.current = true;
    onConfirm(ok);
  };

  return (
    <AlertDialog
      onOpenChange={(nextOpen) => {
        if (nextOpen) {
          closedByActionRef.current = false;
          return;
        }

        if (!closedByActionRef.current) {
          onConfirm(false);
        }
      }}
      open={open}
    >
      <AlertDialogContent className="max-w-md rounded-2xl border border-border shadow-lg">
        <AlertDialogHeader className="space-y-2">
          <AlertDialogTitle className="text-lg font-semibold">{title}</AlertDialogTitle>
          <AlertDialogDescription aria-live="assertive" className="text-sm text-muted-foreground">
            {description}
          </AlertDialogDescription>
        </AlertDialogHeader>

        <AlertDialogFooter className="mt-12">
          <AlertDialogCancel autoFocus className="min-w-[120px]" onClick={() => handleClose(false)}>
            {cancelLabel}
          </AlertDialogCancel>

          <AlertDialogAction
            className="min-w-[120px] bg-destructive text-white hover:bg-destructive/90"
            onClick={() => handleClose(true)}
          >
            {confirmLabel}
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
};
