import { useState } from 'react'
import { isAxiosError } from 'axios'
import { AlertCircle } from 'lucide-react'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { Alert, AlertDescription } from '@/components/ui/alert'
import type { Rubro } from '../types'

interface DeleteRubroDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  rubro: Rubro
  onConfirm: (id: number) => Promise<void> | void
}

function resolveDeleteError(err: unknown): string | null {
  if (!err) return null
  if (isAxiosError(err) && err.response?.data) {
    const data = err.response.data as { error?: string; message?: string }
    return data.message ?? data.error ?? 'Error al desactivar el rubro'
  }
  // Also handle raw rejection objects (from tests)
  const errObj = err as { response?: { status?: number; data?: { message?: string } } }
  if (errObj?.response?.data?.message) {
    return errObj.response.data.message
  }
  return 'Error al desactivar el rubro'
}

export function DeleteRubroDialog({
  open,
  onOpenChange,
  rubro,
  onConfirm,
}: DeleteRubroDialogProps) {
  const [error, setError] = useState<string | null>(null)
  const [isPending, setIsPending] = useState(false)

  async function handleConfirm() {
    setError(null)
    setIsPending(true)
    try {
      await onConfirm(rubro.id)
      onOpenChange(false)
    } catch (err) {
      setError(resolveDeleteError(err))
    } finally {
      setIsPending(false)
    }
  }

  return (
    <AlertDialog open={open} onOpenChange={onOpenChange}>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Desactivar rubro</AlertDialogTitle>
          <AlertDialogDescription>
            ¿Desactivar rubro &ldquo;{rubro.nombre}&rdquo;? Los avisos asociados conservan la
            referencia pero el rubro no aparecerá en listados activos.
          </AlertDialogDescription>
        </AlertDialogHeader>

        {error && (
          <Alert variant="destructive">
            <AlertCircle className="h-4 w-4" />
            <AlertDescription>{error}</AlertDescription>
          </Alert>
        )}

        <AlertDialogFooter>
          <AlertDialogCancel disabled={isPending}>Cancelar</AlertDialogCancel>
          <AlertDialogAction onClick={handleConfirm} disabled={isPending}>
            {isPending ? 'Procesando...' : 'Desactivar'}
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  )
}
