"use client"

import * as React from "react"
import type { LucideIcon } from "lucide-react"

import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogMedia,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog"

export type DeleteConfirmDialogProps = {
  open: boolean
  onOpenChange: (open: boolean) => void
  title: React.ReactNode
  description: React.ReactNode
  /** Optional icon shown in a destructive badge above the title (e.g. Trash2). */
  icon?: LucideIcon
  confirmLabel?: string
  confirmingLabel?: string
  className?: string
  /** Reject/throw to keep the dialog open — the caller surfaces its own error toast. */
  onConfirm: () => Promise<void>
}

/**
 * Shared "are you sure?" delete dialog: keeps itself open and disables its
 * buttons while onConfirm is in flight, closes only once onConfirm resolves.
 * Extracted from the near-identical emails/deepdex delete dialogs.
 */
export function DeleteConfirmDialog({
  open,
  onOpenChange,
  title,
  description,
  icon: Icon,
  confirmLabel = "Delete",
  confirmingLabel = "Deleting...",
  className,
  onConfirm,
}: DeleteConfirmDialogProps) {
  const [isDeleting, setIsDeleting] = React.useState(false)

  const handleConfirm = async () => {
    setIsDeleting(true)
    try {
      await onConfirm()
      onOpenChange(false)
    } catch {
      // onConfirm surfaces its own error (e.g. toast); keep the dialog open to retry.
    } finally {
      setIsDeleting(false)
    }
  }

  return (
    <AlertDialog
      open={open}
      onOpenChange={(next) => {
        if (isDeleting) return
        onOpenChange(next)
      }}
    >
      <AlertDialogContent className={className}>
        <AlertDialogHeader>
          {Icon ? (
            <AlertDialogMedia className="bg-destructive/10 text-destructive">
              <Icon className="size-5" />
            </AlertDialogMedia>
          ) : null}
          <AlertDialogTitle>{title}</AlertDialogTitle>
          <AlertDialogDescription>{description}</AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>
          <AlertDialogAction
            variant="destructive"
            disabled={isDeleting}
            onClick={(event) => {
              event.preventDefault()
              void handleConfirm()
            }}
          >
            {isDeleting ? confirmingLabel : confirmLabel}
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  )
}
