import { useEffect } from 'react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { isAxiosError } from 'axios'
import { AlertCircle } 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 {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form'
import { Input } from '@/components/ui/input'
import { todayArgentina } from '@/lib/dateFormat'
import { useAddProductPrice } from '../hooks/useAddProductPrice'

// ─── Schema (Zod, espejo del backend) ────────────────────────────────────────

const addPriceSchema = z.object({
  price: z.coerce
    .number('Debe ser un número')
    .positive('El precio debe ser mayor a cero.'),
  priceValidFrom: z
    .string()
    .min(1, 'La fecha es requerida.')
    .regex(/^\d{4}-\d{2}-\d{2}$/, 'Formato yyyy-MM-dd requerido.')
    .refine(
      (v) => v >= todayArgentina(),
      'La fecha no puede ser anterior a hoy.',
    ),
})

type AddPriceFormRaw = {
  price: string
  priceValidFrom: string
}

type AddPriceFormOutput = z.infer<typeof addPriceSchema>

// ─── 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 }
    if (err.response.status === 409) {
      return data.message ?? 'La fecha debe ser posterior al precio vigente.'
    }
    if (err.response.status === 404) {
      return data.message ?? 'Producto no encontrado.'
    }
    return data.message ?? data.error ?? 'Error al guardar el precio.'
  }
  return 'Error al guardar el precio. Intentá de nuevo.'
}

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

interface AddProductPriceDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  productId: number
}

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

export function AddProductPriceDialog({
  open,
  onOpenChange,
  productId,
}: AddProductPriceDialogProps) {
  const mutation = useAddProductPrice(productId)

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const form = useForm<AddPriceFormRaw>({
    resolver: zodResolver(addPriceSchema) as any,
    defaultValues: {
      price: '',
      priceValidFrom: '',
    },
    mode: 'onSubmit',
  })

  // Reset form and mutation state when dialog opens
  useEffect(() => {
    if (open) {
      form.reset({ price: '', priceValidFrom: '' })
      mutation.reset()
    }
  }, [open]) // eslint-disable-line react-hooks/exhaustive-deps

  const backendError = resolveBackendError(mutation.error)
  const today = todayArgentina()

  function handleSubmit(values: AddPriceFormOutput) {
    mutation.mutate(
      { price: values.price, priceValidFrom: values.priceValidFrom },
      {
        onSuccess: () => {
          onOpenChange(false)
        },
      },
    )
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Programar nuevo precio</DialogTitle>
          <DialogDescription>
            Ingresá el nuevo precio y la fecha desde la que estará vigente. El
            precio actual quedará cerrado.
          </DialogDescription>
        </DialogHeader>

        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(
              handleSubmit as unknown as Parameters<typeof form.handleSubmit>[0],
            )}
            className="space-y-4"
            noValidate
          >
            {backendError && (
              <Alert variant="destructive">
                <AlertCircle className="h-4 w-4" />
                <AlertDescription>{backendError}</AlertDescription>
              </Alert>
            )}

            {/* Precio */}
            <FormField
              control={form.control}
              name="price"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Precio</FormLabel>
                  <FormControl>
                    <Input
                      {...field}
                      type="number"
                      step="0.01"
                      min="0.01"
                      placeholder="0.00"
                      aria-label="Precio"
                      disabled={mutation.isPending}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* Vigente desde */}
            <FormField
              control={form.control}
              name="priceValidFrom"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Vigente desde</FormLabel>
                  <FormControl>
                    <Input
                      {...field}
                      type="date"
                      min={today}
                      aria-label="Vigente desde"
                      disabled={mutation.isPending}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <DialogFooter className="gap-2">
              <Button
                type="button"
                variant="ghost"
                onClick={() => onOpenChange(false)}
                disabled={mutation.isPending}
              >
                Cancelar
              </Button>
              <Button type="submit" disabled={mutation.isPending}>
                {mutation.isPending ? 'Guardando...' : 'Guardar'}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}
