import { useState } from 'react'
import { isAxiosError } from 'axios'
import { AlertCircle } from 'lucide-react'
import { toast } from 'sonner'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { ProductForm } from './ProductForm'
import type { ProductFormOutput } from './ProductForm'
import { useCreateProduct } from '../hooks/useCreateProduct'
import { useUpdateProduct } from '../hooks/useUpdateProduct'
import type { ProductDetail } from '../types'
import { useProductTypes } from '@/features/product-types/hooks/useProductTypes'

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

function resolveBackendError(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 guardar el producto'
  }
  const errObj = err as { response?: { data?: { message?: string } } }
  if (errObj?.response?.data?.message) {
    return errObj.response.data.message
  }
  return 'Error al guardar el producto'
}

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

interface ProductFormDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  product?: ProductDetail
  onSuccess?: () => void
}

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

export function ProductFormDialog({
  open,
  onOpenChange,
  product,
  onSuccess,
}: ProductFormDialogProps) {
  const [backendError, setBackendError] = useState<string | null>(null)

  const isEdit = !!product
  const { mutateAsync: createProduct, isPending: creating } = useCreateProduct()
  const { mutateAsync: updateProduct, isPending: updating } = useUpdateProduct()
  const isPending = creating || updating

  // Fetch active product types so ProductForm can derive conditional fields
  const { data: productTypesPaged } = useProductTypes({ activo: true })
  const productTypes = productTypesPaged?.items ?? []

  async function handleSubmit(values: ProductFormOutput) {
    setBackendError(null)
    try {
      if (isEdit) {
        await updateProduct({
          id: product.id,
          data: {
            nombre: values.nombre,
            rubroId: values.rubroId,
            basePrice: values.basePrice,
            priceDurationDays: values.priceDurationDays,
          },
        })
        toast.success('Producto actualizado')
      } else {
        await createProduct({
          nombre: values.nombre,
          medioId: values.medioId,
          productTypeId: values.productTypeId,
          rubroId: values.rubroId,
          basePrice: values.basePrice,
          priceDurationDays: values.priceDurationDays,
        })
        toast.success('Producto creado')
      }
      onOpenChange(false)
      onSuccess?.()
    } catch (err) {
      const msg = resolveBackendError(err)
      setBackendError(msg)
      if (
        !isAxiosError(err) ||
        (err.response?.status !== 409 && err.response?.status !== 422 && err.response?.status !== 400)
      ) {
        toast.error(isEdit ? 'Error al actualizar producto' : 'Error al crear producto')
      }
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-lg">
        <DialogHeader>
          <DialogTitle>{isEdit ? 'Editar producto' : 'Nuevo producto'}</DialogTitle>
          <DialogDescription>
            {isEdit
              ? `Modificá los datos del producto "${product?.nombre ?? ''}".`
              : 'Completá los datos para crear un nuevo producto.'}
          </DialogDescription>
        </DialogHeader>

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

        <ProductForm
          productTypes={productTypes}
          defaultValues={product}
          onSubmit={handleSubmit}
          onCancel={() => onOpenChange(false)}
          isPending={isPending}
          isEdit={isEdit}
        />
      </DialogContent>
    </Dialog>
  )
}
