"use client";

import * as React from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";

// Local aliases for use inside this file. External consumers can import the
// canonical AlertDialog* names from `@/components/ui/alert-dialog` (re-exports below).
const AlertDialogContent = DialogContent;
const AlertDialogHeader = DialogHeader;
const AlertDialogTitle = DialogTitle;
const AlertDialogDescription = DialogDescription;
const AlertDialogFooter = DialogFooter;

// ──────────────────────────────────────────────────────────────────────
// AlertDialog — destructive-confirm variant of Dialog
// ──────────────────────────────────────────────────────────────────────
// Mechanics differ from Dialog in two ways:
//   1. modal=true on the underlying Dialog so backdrop clicks don't dismiss
//   2. Action / Cancel buttons are the only legitimate exits
// ──────────────────────────────────────────────────────────────────────

export function AlertDialog({
  open,
  defaultOpen,
  onOpenChange,
  children,
}: {
  open?: boolean;
  defaultOpen?: boolean;
  onOpenChange?: (open: boolean) => void;
  children: React.ReactNode;
}) {
  return (
    <Dialog open={open} defaultOpen={defaultOpen} onOpenChange={onOpenChange} modal>
      {children}
    </Dialog>
  );
}

export { AlertDialogContent, AlertDialogHeader, AlertDialogTitle, AlertDialogDescription, AlertDialogFooter };
export { DialogBody as AlertDialogBody } from "@/components/ui/dialog";

export function AlertDialogAction({
  children,
  destructive,
  onClick,
  className,
  autoFocus,
}: {
  children: React.ReactNode;
  destructive?: boolean;
  onClick?: () => void;
  className?: string;
  autoFocus?: boolean;
}) {
  return (
    <Button
      autoFocus={autoFocus}
      variant={destructive ? "destructive" : "default"}
      onClick={onClick}
      className={className}
    >
      {children}
    </Button>
  );
}

export function AlertDialogCancel({
  children = "Cancel",
  onClick,
  className,
  autoFocus,
}: {
  children?: React.ReactNode;
  onClick?: () => void;
  className?: string;
  autoFocus?: boolean;
}) {
  return (
    <Button
      autoFocus={autoFocus}
      variant="outline"
      onClick={onClick}
      className={cn(className)}
    >
      {children}
    </Button>
  );
}

// ──────────────────────────────────────────────────────────────────────
// useAlertConfirm — drop-in replacement for window.confirm
// ──────────────────────────────────────────────────────────────────────
// Usage in a component:
//
//   const { confirm, AlertConfirmPortal } = useAlertConfirm();
//
//   async function handleDelete() {
//     const ok = await confirm({
//       title: "Delete bill?",
//       description: "This permanently removes the record. Cannot be undone.",
//       actionLabel: "Delete",
//       destructive: true,
//     });
//     if (ok) actuallyDelete();
//   }
//
//   return <>... <AlertConfirmPortal /></>;
//
// The portal is rendered exactly once. Subsequent confirm() calls reuse the
// same dialog instance (queued: only one prompt at a time).
// ──────────────────────────────────────────────────────────────────────

export type AlertConfirmOptions = {
  title: React.ReactNode;
  description?: React.ReactNode;
  actionLabel?: string;
  cancelLabel?: string;
  destructive?: boolean;
};

type PendingPrompt = {
  opts: AlertConfirmOptions;
  resolve: (ok: boolean) => void;
};

export function useAlertConfirm() {
  const [pending, setPending] = React.useState<PendingPrompt | null>(null);

  const confirm = React.useCallback(
    (opts: AlertConfirmOptions): Promise<boolean> => {
      return new Promise<boolean>((resolve) => {
        setPending({ opts, resolve });
      });
    },
    [],
  );

  const handleResolve = React.useCallback(
    (ok: boolean) => {
      if (pending) {
        pending.resolve(ok);
        setPending(null);
      }
    },
    [pending],
  );

  const AlertConfirmPortal = React.useCallback(() => {
    if (!pending) return null;
    const { opts } = pending;
    return (
      <AlertDialog
        open
        onOpenChange={(open) => {
          if (!open) handleResolve(false);
        }}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{opts.title}</AlertDialogTitle>
            {opts.description && (
              <AlertDialogDescription>{opts.description}</AlertDialogDescription>
            )}
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => handleResolve(false)} autoFocus>
              {opts.cancelLabel ?? "Cancel"}
            </AlertDialogCancel>
            <AlertDialogAction
              destructive={opts.destructive}
              onClick={() => handleResolve(true)}
            >
              {opts.actionLabel ?? "Confirm"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    );
  }, [pending, handleResolve]);

  return { confirm, AlertConfirmPortal };
}
