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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { todayArgentina } from '@/lib/formatters'
import { CHARGEABLE_CHAR_CATEGORIES, CATEGORY_LABELS } from '../categories'
import { useCreateChargeableCharConfig } from '../hooks/useCreateChargeableCharConfig'
import { useSchedulePriceChange } from '../hooks/useSchedulePriceChange'
import { SymbolInput } from './SymbolInput'
import { ProductTypeSelect } from './ProductTypeSelect'
import type { ChargeableCharConfig } from '../types'

// ─── Emoji regex (same as SymbolInput) ───────────────────────────────────────
const EMOJI_REGEX = /\p{Extended_Pictographic}/u

// ─── Schemas ─────────────────────────────────────────────────────────────────

const createSchema = z.object({
  productTypeId: z.number().nullable().optional(),
  symbol: z
    .string()
    .min(1, 'El símbolo es requerido.')
    .max(4, 'Máximo 4 caracteres.')
    .refine((s) => !EMOJI_REGEX.test(s), 'Los emojis no están permitidos.'),
  category: z.enum(['Currency', 'Percentage', 'Exclamation', 'Question', 'Other'], {
    error: 'La categoría es requerida.',
  }),
  pricePerUnit: z.coerce
    .number('Debe ser un número.')
    .positive('El precio debe ser mayor a cero.'),
  validFrom: 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.'),
})

const schedulePriceSchema = z.object({
  pricePerUnit: z.coerce
    .number('Debe ser un número.')
    .positive('El precio debe ser mayor a cero.'),
  validFrom: 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 CreateFormRaw = {
  productTypeId?: number | null
  symbol: string
  category: string
  pricePerUnit: string
  validFrom: string
}

type SchedulePriceFormRaw = {
  pricePerUnit: string
  validFrom: string
}

// ─── 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; code?: string }
    if (err.response.status === 409) {
      return data.message ?? 'No se pueden retrodatar precios. Elegí una fecha posterior.'
    }
    if (err.response.status === 400 && data.code === 'CHARGEABLE_CHAR_FORWARD_ONLY') {
      return 'No se pueden retrodatar precios.'
    }
    return data.message ?? data.error ?? 'Error al guardar.'
  }
  return 'Error al guardar. Intentá de nuevo.'
}

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

interface ChargeableCharFormDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  mode: 'create' | 'schedulePrice'
  /** Required when mode is 'schedulePrice' */
  config?: ChargeableCharConfig
}

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

export function ChargeableCharFormDialog({
  open,
  onOpenChange,
  mode,
  config,
}: ChargeableCharFormDialogProps) {
  const createMutation = useCreateChargeableCharConfig()
  const scheduleMutation = useSchedulePriceChange(config?.id ?? 0)

  const isSchedule = mode === 'schedulePrice'
  const activeMutation = isSchedule ? scheduleMutation : createMutation

  // ── Create form ──────────────────────────────────────────────────────────
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const createForm = useForm<CreateFormRaw>({
    resolver: zodResolver(createSchema) as any,
    defaultValues: { productTypeId: null, symbol: '', category: '', pricePerUnit: '', validFrom: '' },
    mode: 'onSubmit',
  })

  // ── SchedulePrice form ───────────────────────────────────────────────────
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const scheduleForm = useForm<SchedulePriceFormRaw>({
    resolver: zodResolver(schedulePriceSchema) as any,
    defaultValues: { pricePerUnit: '', validFrom: '' },
    mode: 'onSubmit',
  })

  useEffect(() => {
    if (open) {
      createForm.reset({ productTypeId: null, symbol: '', category: '', pricePerUnit: '', validFrom: '' })
      scheduleForm.reset({ pricePerUnit: '', validFrom: '' })
      createMutation.reset()
      scheduleMutation.reset()
    }
  }, [open]) // eslint-disable-line react-hooks/exhaustive-deps

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

  function handleCreateSubmit(values: z.infer<typeof createSchema>) {
    createMutation.mutate(
      {
        productTypeId: values.productTypeId ?? null,
        symbol: values.symbol,
        category: values.category as ChargeableCharConfig['category'],
        pricePerUnit: values.pricePerUnit,
        validFrom: values.validFrom,
      },
      {
        onSuccess: () => onOpenChange(false),
      },
    )
  }

  function handleScheduleSubmit(values: z.infer<typeof schedulePriceSchema>) {
    scheduleMutation.mutate(
      {
        newPricePerUnit: values.pricePerUnit,
        newValidFrom: values.validFrom,
      },
      {
        onSuccess: () => onOpenChange(false),
      },
    )
  }

  const isPending = activeMutation.isPending

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>
            {isSchedule ? 'Programar cambio de precio' : 'Nuevo carácter tasable'}
          </DialogTitle>
          <DialogDescription>
            {isSchedule
              ? `Programá un nuevo precio para "${config?.symbol}" a partir de la fecha elegida.`
              : 'Completá los datos para crear un nuevo carácter tasable.'}
          </DialogDescription>
        </DialogHeader>

        {backendError && (
          <Alert variant="destructive">
            <AlertCircle className="h-4 w-4" />
            <AlertDescription>{backendError}</AlertDescription>
          </Alert>
        )}

        {/* ── CREATE MODE ─────────────────────────────────────────────────── */}
        {!isSchedule && (
          <Form {...createForm}>
            <form
              onSubmit={createForm.handleSubmit(
                handleCreateSubmit as unknown as Parameters<typeof createForm.handleSubmit>[0],
              )}
              className="space-y-4"
              noValidate
            >
              {/* Tipo de producto */}
              <FormField
                control={createForm.control}
                name="productTypeId"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Tipo de producto</FormLabel>
                    <FormControl>
                      <ProductTypeSelect
                        value={field.value}
                        onValueChange={(v) => field.onChange(v ?? null)}
                        globalOptionLabel="Global (todos los tipos)"
                        placeholder="Seleccioná un tipo de producto"
                        disabled={isPending}
                        aria-label="Tipo de producto"
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Símbolo */}
              <FormField
                control={createForm.control}
                name="symbol"
                render={({ field, fieldState }) => (
                  <FormItem>
                    <FormLabel htmlFor="symbol-input">Símbolo</FormLabel>
                    <FormControl>
                      <SymbolInput
                        id="symbol-input"
                        aria-label="Símbolo"
                        name={field.name}
                        value={field.value}
                        onChange={field.onChange}
                        error={fieldState.error?.message}
                        disabled={isPending}
                        placeholder="ej: $"
                      />
                    </FormControl>
                    {!fieldState.error && <FormMessage />}
                  </FormItem>
                )}
              />

              {/* Categoría */}
              <FormField
                control={createForm.control}
                name="category"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Categoría</FormLabel>
                    <FormControl>
                      <Select
                        value={field.value}
                        onValueChange={field.onChange}
                        disabled={isPending}
                      >
                        <SelectTrigger aria-label="Categoría">
                          <SelectValue placeholder="Seleccioná una categoría" />
                        </SelectTrigger>
                        <SelectContent>
                          {CHARGEABLE_CHAR_CATEGORIES.map((cat) => (
                            <SelectItem key={cat} value={cat}>
                              {CATEGORY_LABELS[cat]}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Precio */}
              <FormField
                control={createForm.control}
                name="pricePerUnit"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Precio por unidad</FormLabel>
                    <FormControl>
                      <Input
                        {...field}
                        type="number"
                        step="0.0001"
                        min="0.0001"
                        placeholder="0.0000"
                        aria-label="Precio por unidad"
                        disabled={isPending}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

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

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

        {/* ── SCHEDULE PRICE MODE ─────────────────────────────────────────── */}
        {isSchedule && (
          <Form {...scheduleForm}>
            <form
              onSubmit={scheduleForm.handleSubmit(
                handleScheduleSubmit as unknown as Parameters<typeof scheduleForm.handleSubmit>[0],
              )}
              className="space-y-4"
              noValidate
            >
              {/* Read-only info */}
              {config && (
                <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">{config.symbol}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">Categoría: </span>
                    <span>{CATEGORY_LABELS[config.category]}</span>
                  </div>
                </div>
              )}

              {/* Nuevo precio */}
              <FormField
                control={scheduleForm.control}
                name="pricePerUnit"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Nuevo precio por unidad</FormLabel>
                    <FormControl>
                      <Input
                        {...field}
                        type="number"
                        step="0.0001"
                        min="0.0001"
                        placeholder="0.0000"
                        aria-label="Precio por unidad"
                        disabled={isPending}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

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

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