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 {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Alert, AlertDescription } from '@/components/ui/alert'
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form'
import type { Rubro } from '../types'

const rubroFormSchema = z.object({
  nombre: z
    .string()
    .min(1, 'El nombre es requerido')
    .max(200, 'Máximo 200 caracteres'),
  tarifarioBaseId: z
    .string()
    .transform((val) => (val === '' ? null : Number(val)))
    .pipe(z.number().int().positive('Debe ser un número positivo').nullable())
    .optional()
    .nullable(),
})

export type RubroFormValues = {
  nombre: string
  tarifarioBaseId?: number | null
}

interface RubroFormDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  rubro?: Rubro
  parentId?: number | null
  onSubmit: (values: RubroFormValues) => void
  isPending?: boolean
  error?: unknown
}

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 (data.error === 'rubro_nombre_duplicado') {
      return data.message ?? 'Ya existe un rubro con ese nombre bajo este padre'
    }
    if (data.error === 'rubro_max_depth_exceeded') {
      return data.message ?? 'Profundidad máxima 10 niveles alcanzada'
    }
    return data.message ?? data.error ?? 'Error al guardar el rubro'
  }
  return 'Error al guardar el rubro'
}

export function RubroFormDialog({
  open,
  onOpenChange,
  rubro,
  onSubmit,
  isPending = false,
  error,
}: RubroFormDialogProps) {
  const isEdit = !!rubro

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const form = useForm<RubroFormValues>({
    resolver: zodResolver(rubroFormSchema) as any,
    defaultValues: {
      nombre: rubro?.nombre ?? '',
      tarifarioBaseId: rubro?.tarifarioBaseId ?? null,
    },
  })

  useEffect(() => {
    if (open) {
      form.reset({
        nombre: rubro?.nombre ?? '',
        tarifarioBaseId: rubro?.tarifarioBaseId ?? null,
      })
    }
  }, [open, rubro, form])

  const backendError = resolveBackendError(error)

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

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4" noValidate>
            {backendError && (
              <Alert variant="destructive">
                <AlertCircle className="h-4 w-4" />
                <AlertDescription>{backendError}</AlertDescription>
              </Alert>
            )}

            <FormField
              control={form.control}
              name="nombre"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Nombre</FormLabel>
                  <FormControl>
                    <Input
                      {...field}
                      type="text"
                      disabled={isPending}
                      placeholder="Nombre del rubro"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="tarifarioBaseId"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Tarifario Base ID (opcional)</FormLabel>
                  <FormControl>
                    <Input
                      {...field}
                      value={field.value != null ? String(field.value) : ''}
                      onChange={(e) => field.onChange(e.target.value === '' ? null : e.target.value)}
                      type="number"
                      min={1}
                      disabled={isPending}
                      placeholder="ID numérico (opcional)"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <div className="flex justify-end gap-2 pt-2">
              <Button
                type="button"
                variant="outline"
                onClick={() => onOpenChange(false)}
                disabled={isPending}
              >
                Cancelar
              </Button>
              <Button type="submit" disabled={isPending}>
                {isPending ? 'Guardando...' : isEdit ? 'Guardar cambios' : 'Crear'}
              </Button>
            </div>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}
