import { toast } from 'sonner'
import { AlertTriangle } from 'lucide-react'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Button } from '@/components/ui/button'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { useDeleteChargeableCharConfig } from '../hooks/useDeleteChargeableCharConfig'

interface DeleteChargeableCharConfigDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  /** The config id to delete */
  configId: number
  /** Symbol label for the warning text */
  symbol: string
}

export function DeleteChargeableCharConfigDialog({
  open,
  onOpenChange,
  configId,
  symbol,
}: DeleteChargeableCharConfigDialogProps) {
  const deleteMutation = useDeleteChargeableCharConfig()

  function handleConfirm() {
    deleteMutation.mutate(configId, {
      onSuccess: () => {
        toast.success(`Símbolo '${symbol}' eliminado correctamente.`)
        onOpenChange(false)
        deleteMutation.reset()
      },
      onError: () => {
        toast.error('No se pudo eliminar el símbolo. Intentá de nuevo.')
      },
    })
  }

  function handleClose(open: boolean) {
    if (!deleteMutation.isPending) {
      deleteMutation.reset()
      onOpenChange(open)
    }
  }

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Eliminar carácter tasable</DialogTitle>
          <DialogDescription>
            Esta acción eliminará permanentemente la tasación del símbolo '{symbol}'.
            ¿Estás seguro?
          </DialogDescription>
        </DialogHeader>

        <Alert variant="destructive">
          <AlertTriangle className="h-4 w-4" />
          <AlertDescription>
            La eliminación es posible porque este carácter no está en uso.
          </AlertDescription>
        </Alert>

        <DialogFooter className="gap-2">
          <Button
            type="button"
            variant="ghost"
            onClick={() => handleClose(false)}
            disabled={deleteMutation.isPending}
          >
            Cancelar
          </Button>
          <Button
            type="button"
            variant="destructive"
            onClick={handleConfirm}
            disabled={deleteMutation.isPending}
          >
            {deleteMutation.isPending ? 'Eliminando...' : 'Eliminar'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
