import { useState } from 'react'
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 { ProductListItem } from '../types'

// ─── Error resolver ────────────────────────────────────────────────────────────

function resolveDeactivateError(err: unknown): string | null {
  if (!err) return null
  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 producto'
}

// ─── Props ────────────────────────────────────────────────────────────────────

interface DeactivateProductDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  product: ProductListItem
  onConfirm: (id: number) => Promise<void> | void
}

// ─── Component ────────────────────────────────────────────────────────────────

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

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

  return (
    <AlertDialog open={open} onOpenChange={onOpenChange}>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Desactivar producto</AlertDialogTitle>
          <AlertDialogDescription>
            ¿Desactivar el producto &ldquo;{product.nombre}&rdquo;? El producto no
            aparecerá en los 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>
  )
}
