import { useState } from 'react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { formatCivilDate } from '@/lib/formatters'
import { useProductTypes } from '../../product-types/hooks/useProductTypes'
import { useCreateChargeableCharConfig } from '../hooks/useCreateChargeableCharConfig'
import type { ChargeableCharCategory } from '../types'

interface CopyToAllProductTypesDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  symbol: string
  pricePerUnit: number
  /** yyyy-MM-dd */
  validFrom: string
  category: ChargeableCharCategory
}

/**
 * Confirmation dialog that creates rows for all active ProductTypes
 * with the same symbol/price/validFrom/category.
 *
 * Uses Promise.allSettled — if one productType fails, the rest still proceed.
 * Summary toast shows success/failure counts.
 */
export function CopyToAllProductTypesDialog({
  open,
  onOpenChange,
  symbol,
  pricePerUnit,
  validFrom,
  category,
}: CopyToAllProductTypesDialogProps) {
  const { data: ptData } = useProductTypes({ activo: true, pageSize: 200 })
  const productTypes = ptData?.items ?? []
  const createMutation = useCreateChargeableCharConfig()
  const [isProcessing, setIsProcessing] = useState(false)

  async function handleConfirm() {
    if (productTypes.length === 0) return
    setIsProcessing(true)
    try {
      // Promise.allSettled: partial failure doesn't block the rest
      const results = await Promise.allSettled(
        productTypes.map((pt) =>
          createMutation.mutateAsync({
            productTypeId: pt.id,
            symbol,
            category,
            pricePerUnit,
            validFrom,
          }),
        ),
      )
      const succeeded = results.filter((r) => r.status === 'fulfilled').length
      const failed = results.filter((r) => r.status === 'rejected').length

      if (failed === 0) {
        toast.success(`Copiado a ${succeeded} tipo${succeeded !== 1 ? 's' : ''} exitosamente.`)
      } else {
        toast.error(
          `${succeeded} exitosos, ${failed} fallidos. Revisá los errores en la lista.`,
        )
      }
      onOpenChange(false)
    } finally {
      setIsProcessing(false)
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Copiar a todos los tipos de producto</DialogTitle>
          <DialogDescription>
            Se creará una configuración para cada tipo de producto activo con los siguientes datos.
          </DialogDescription>
        </DialogHeader>

        {/* Preview */}
        <div className="rounded-md bg-muted p-3 text-sm space-y-1">
          <div>
            <span className="text-muted-foreground">Símbolo: </span>
            <span className="font-mono font-semibold">{symbol}</span>
          </div>
          <div>
            <span className="text-muted-foreground">Precio/unidad: </span>
            <span>{pricePerUnit}</span>
          </div>
          <div>
            <span className="text-muted-foreground">Vigente desde: </span>
            <span>{formatCivilDate(validFrom)}</span>
          </div>
        </div>

        {/* List of product types */}
        {productTypes.length > 0 ? (
          <div className="max-h-48 overflow-y-auto space-y-1 text-sm">
            {productTypes.map((pt) => (
              <div key={pt.id} className="flex items-center gap-2 py-1">
                <span className="text-muted-foreground">•</span>
                <span>{pt.nombre}</span>
              </div>
            ))}
          </div>
        ) : (
          <p className="text-sm text-muted-foreground">Cargando tipos de producto...</p>
        )}

        <DialogFooter className="gap-2">
          <Button
            type="button"
            variant="ghost"
            onClick={() => onOpenChange(false)}
            disabled={isProcessing}
          >
            Cancelar
          </Button>
          <Button
            type="button"
            onClick={handleConfirm}
            disabled={isProcessing || productTypes.length === 0}
          >
            {isProcessing ? 'Copiando...' : `Confirmar (${productTypes.length} tipos)`}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
