import { useEffect } from 'react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form'

// ─── Schema ───────────────────────────────────────────────────────────────────

function nullablePositiveInt() {
  return z
    .string()
    .optional()
    .transform((v) => (v === '' || v == null ? null : Number(v)))
    .pipe(z.number().int().positive().nullable())
}

function nullablePositiveDecimal() {
  return z
    .string()
    .optional()
    .transform((v) => (v === '' || v == null ? null : Number(v)))
    .pipe(z.number().positive().nullable())
}

const productTypeFormSchema = z.object({
  nombre: z.string().trim().min(1, 'Nombre requerido').max(100, 'Máximo 100 caracteres'),
  hasDuration: z.boolean(),
  requiresText: z.boolean(),
  requiresCategory: z.boolean(),
  isBundle: z.boolean(),
  allowImages: z.boolean(),
  maxImages: nullablePositiveInt(),
  maxImageSizeMB: nullablePositiveDecimal(),
  maxImageWidth: nullablePositiveInt(),
  maxImageHeight: nullablePositiveInt(),
})

// Raw form field types (strings before zod transforms)
type ProductTypeFormRaw = {
  nombre: string
  hasDuration: boolean
  requiresText: boolean
  requiresCategory: boolean
  isBundle: boolean
  allowImages: boolean
  maxImages: string
  maxImageSizeMB: string
  maxImageWidth: string
  maxImageHeight: string
}

// Output type after zod transforms (what onSubmit receives at runtime)
export type ProductTypeFormOutput = {
  nombre: string
  hasDuration: boolean
  requiresText: boolean
  requiresCategory: boolean
  isBundle: boolean
  allowImages: boolean
  maxImages: number | null
  maxImageSizeMB: number | null
  maxImageWidth: number | null
  maxImageHeight: number | null
}

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

export interface ProductTypeFormDefaultValues {
  nombre?: string
  hasDuration?: boolean
  requiresText?: boolean
  requiresCategory?: boolean
  isBundle?: boolean
  allowImages?: boolean
  maxImages?: number | null
  maxImageSizeMB?: number | null
  maxImageWidth?: number | null
  maxImageHeight?: number | null
}

interface ProductTypeFormProps {
  defaultValues?: ProductTypeFormDefaultValues
  onSubmit: (values: ProductTypeFormOutput) => void
  onCancel: () => void
  isPending?: boolean
  isEdit?: boolean
}

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

export function ProductTypeForm({
  defaultValues,
  onSubmit,
  onCancel,
  isPending = false,
  isEdit = false,
}: ProductTypeFormProps) {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const form = useForm<ProductTypeFormRaw>({
    resolver: zodResolver(productTypeFormSchema) as any,
    defaultValues: {
      nombre: defaultValues?.nombre ?? '',
      hasDuration: defaultValues?.hasDuration ?? false,
      requiresText: defaultValues?.requiresText ?? false,
      requiresCategory: defaultValues?.requiresCategory ?? false,
      isBundle: defaultValues?.isBundle ?? false,
      allowImages: defaultValues?.allowImages ?? false,
      maxImages: defaultValues?.maxImages != null ? String(defaultValues.maxImages) : '',
      maxImageSizeMB: defaultValues?.maxImageSizeMB != null ? String(defaultValues.maxImageSizeMB) : '',
      maxImageWidth: defaultValues?.maxImageWidth != null ? String(defaultValues.maxImageWidth) : '',
      maxImageHeight: defaultValues?.maxImageHeight != null ? String(defaultValues.maxImageHeight) : '',
    },
  })

  const allowImages = form.watch('allowImages')

  useEffect(() => {
    form.reset({
      nombre: defaultValues?.nombre ?? '',
      hasDuration: defaultValues?.hasDuration ?? false,
      requiresText: defaultValues?.requiresText ?? false,
      requiresCategory: defaultValues?.requiresCategory ?? false,
      isBundle: defaultValues?.isBundle ?? false,
      allowImages: defaultValues?.allowImages ?? false,
      maxImages: defaultValues?.maxImages != null ? String(defaultValues.maxImages) : '',
      maxImageSizeMB: defaultValues?.maxImageSizeMB != null ? String(defaultValues.maxImageSizeMB) : '',
      maxImageWidth: defaultValues?.maxImageWidth != null ? String(defaultValues.maxImageWidth) : '',
      maxImageHeight: defaultValues?.maxImageHeight != null ? String(defaultValues.maxImageHeight) : '',
    })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [defaultValues?.nombre, defaultValues?.allowImages])

  function handleSubmit(data: ProductTypeFormOutput) {
    // Normalize multimedia to null when allowImages=false
    if (!data.allowImages) {
      data = {
        ...data,
        maxImages: null,
        maxImageSizeMB: null,
        maxImageWidth: null,
        maxImageHeight: null,
      }
    }
    onSubmit(data)
  }

  return (
    <Form {...form}>
      <form
        onSubmit={form.handleSubmit(
          handleSubmit as unknown as Parameters<typeof form.handleSubmit>[0],
        )}
        className="space-y-4"
        noValidate
      >
        {/* Nombre */}
        <FormField
          control={form.control}
          name="nombre"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Nombre</FormLabel>
              <FormControl>
                <Input
                  {...field}
                  type="text"
                  disabled={isPending}
                  placeholder="Nombre del tipo de producto"
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        {/* Flags */}
        <div className="grid grid-cols-2 gap-3">
          <FormField
            control={form.control}
            name="hasDuration"
            render={({ field }) => (
              <FormItem className="flex flex-row items-center gap-2 space-y-0">
                <FormControl>
                  <input
                    id="hasDuration"
                    type="checkbox"
                    checked={field.value as boolean}
                    onChange={(e) => field.onChange(e.target.checked)}
                    disabled={isPending}
                    aria-label="Tiene duración"
                    className="h-4 w-4 cursor-pointer"
                  />
                </FormControl>
                <FormLabel htmlFor="hasDuration" className="font-normal cursor-pointer">
                  Tiene duración
                </FormLabel>
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="requiresText"
            render={({ field }) => (
              <FormItem className="flex flex-row items-center gap-2 space-y-0">
                <FormControl>
                  <input
                    id="requiresText"
                    type="checkbox"
                    checked={field.value as boolean}
                    onChange={(e) => field.onChange(e.target.checked)}
                    disabled={isPending}
                    aria-label="Requiere texto"
                    className="h-4 w-4 cursor-pointer"
                  />
                </FormControl>
                <FormLabel htmlFor="requiresText" className="font-normal cursor-pointer">
                  Requiere texto
                </FormLabel>
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="requiresCategory"
            render={({ field }) => (
              <FormItem className="flex flex-row items-center gap-2 space-y-0">
                <FormControl>
                  <input
                    id="requiresCategory"
                    type="checkbox"
                    checked={field.value as boolean}
                    onChange={(e) => field.onChange(e.target.checked)}
                    disabled={isPending}
                    aria-label="Requiere categoría"
                    className="h-4 w-4 cursor-pointer"
                  />
                </FormControl>
                <FormLabel htmlFor="requiresCategory" className="font-normal cursor-pointer">
                  Requiere categoría
                </FormLabel>
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="isBundle"
            render={({ field }) => (
              <FormItem className="flex flex-row items-center gap-2 space-y-0">
                <FormControl>
                  <input
                    id="isBundle"
                    type="checkbox"
                    checked={field.value as boolean}
                    onChange={(e) => field.onChange(e.target.checked)}
                    disabled={isPending}
                    aria-label="Es bundle"
                    className="h-4 w-4 cursor-pointer"
                  />
                </FormControl>
                <FormLabel htmlFor="isBundle" className="font-normal cursor-pointer">
                  Es bundle
                </FormLabel>
              </FormItem>
            )}
          />
        </div>

        {/* Allow Images toggle */}
        <FormField
          control={form.control}
          name="allowImages"
          render={({ field }) => (
            <FormItem className="flex flex-row items-center gap-2 space-y-0">
              <FormControl>
                <input
                  id="allowImages"
                  type="checkbox"
                  checked={field.value as boolean}
                  onChange={(e) => field.onChange(e.target.checked)}
                  disabled={isPending}
                  aria-label="Permite imágenes"
                  className="h-4 w-4 cursor-pointer"
                />
              </FormControl>
              <FormLabel htmlFor="allowImages" className="font-normal cursor-pointer">
                Permite imágenes
              </FormLabel>
            </FormItem>
          )}
        />

        {/* Multimedia fields — always rendered, disabled when allowImages=false */}
        <div className="grid grid-cols-2 gap-3 border rounded-md p-3">
          <FormField
            control={form.control}
            name="maxImages"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Máx. imágenes</FormLabel>
                <FormControl>
                  <Input
                    {...field}
                    type="number"
                    min={1}
                    disabled={isPending || !allowImages}
                    placeholder="Sin límite"
                    aria-label="Máx. imágenes"
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="maxImageSizeMB"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Máx. tamaño (MB)</FormLabel>
                <FormControl>
                  <Input
                    {...field}
                    type="number"
                    min={0.1}
                    step={0.1}
                    disabled={isPending || !allowImages}
                    placeholder="Sin límite"
                    aria-label="Máx. tamaño (MB)"
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="maxImageWidth"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Ancho máx. (px)</FormLabel>
                <FormControl>
                  <Input
                    {...field}
                    type="number"
                    min={1}
                    disabled={isPending || !allowImages}
                    placeholder="Sin límite"
                    aria-label="Ancho máx. (px)"
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="maxImageHeight"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Alto máx. (px)</FormLabel>
                <FormControl>
                  <Input
                    {...field}
                    type="number"
                    min={1}
                    disabled={isPending || !allowImages}
                    placeholder="Sin límite"
                    aria-label="Alto máx. (px)"
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
        </div>

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