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 { 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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { TIPO_MEDIO_OPTIONS } from '../tipoMedio'
import type { MedioDetail } from '../types'

const medioFormSchema = z.object({
  codigo: z
    .string()
    .min(1, 'El código es requerido')
    .max(20, 'Máximo 20 caracteres'),
  nombre: z
    .string()
    .min(1, 'El nombre es requerido')
    .max(100, 'Máximo 100 caracteres'),
  tipo: z.coerce.number<number>().refine((v) => v >= 1, 'Seleccioná un tipo válido'),
  plataformaEmpresaId: z
    .union([z.coerce.number<number>().int().positive('Debe ser un número positivo'), z.literal('')])
    .optional(),
})

export type MedioFormValues = z.infer<typeof medioFormSchema>

interface MedioFormProps {
  /** If provided, the form is in edit mode (código is disabled, form is pre-filled). */
  initialData?: MedioDetail
  isPending: boolean
  error: unknown
  onSubmit: (values: MedioFormValues) => void
}

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 === 'medio_codigo_duplicado') {
      return data.message ?? 'Ya existe un medio con ese código'
    }
    return data.message ?? data.error ?? 'Error al guardar el medio'
  }
  return 'Error al guardar el medio'
}

export function MedioForm({ initialData, isPending, error, onSubmit }: MedioFormProps) {
  const isEdit = !!initialData

  const form = useForm<MedioFormValues>({
    resolver: zodResolver(medioFormSchema),
    defaultValues: {
      codigo: initialData?.codigo ?? '',
      nombre: initialData?.nombre ?? '',
      tipo: initialData?.tipo ?? ('' as unknown as number),
      plataformaEmpresaId: (initialData?.plataformaEmpresaId ?? '') as unknown as undefined,
    },
  })

  useEffect(() => {
    if (initialData) {
      form.reset({
        codigo: initialData.codigo,
        nombre: initialData.nombre,
        tipo: initialData.tipo,
        plataformaEmpresaId: (initialData.plataformaEmpresaId ?? '') as unknown as undefined,
      })
    }
  }, [initialData, form])

  const backendError = resolveBackendError(error)

  return (
    <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="codigo"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Código</FormLabel>
              <FormControl>
                <Input
                  {...field}
                  type="text"
                  disabled={isPending || isEdit}
                  placeholder="Ej: DIARIO01"
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

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

        <FormField
          control={form.control}
          name="tipo"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Tipo</FormLabel>
              <Select
                value={field.value ? String(field.value) : ''}
                onValueChange={(v) => field.onChange(v === '' ? '' : Number(v))}
                disabled={isPending}
              >
                <FormControl>
                  <SelectTrigger className="w-full" aria-label="Tipo">
                    <SelectValue placeholder="Seleccioná un tipo" />
                  </SelectTrigger>
                </FormControl>
                <SelectContent>
                  {TIPO_MEDIO_OPTIONS.map((o) => (
                    <SelectItem key={o.value} value={String(o.value)}>
                      {o.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="plataformaEmpresaId"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Plataforma Empresa ID (opcional)</FormLabel>
              <FormControl>
                <Input
                  {...field}
                  value={field.value ?? ''}
                  onChange={(e) => field.onChange(e.target.value)}
                  type="number"
                  min={1}
                  disabled={isPending}
                  placeholder="ID numérico (opcional)"
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <Button type="submit" disabled={isPending} className="w-full">
          {isPending ? 'Guardando...' : isEdit ? 'Guardar cambios' : 'Crear medio'}
        </Button>
      </form>
    </Form>
  )
}
