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 { useCreateRole } from '../hooks/useCreateRole'
import { useUpdateRole } from '../hooks/useUpdateRole'
import type { RolDto } from '../api/types'

const CODIGO_REGEX = /^[a-z][a-z0-9_]*$/

const createSchema = z.object({
  codigo: z
    .string()
    .min(3, 'Mínimo 3 caracteres')
    .max(30, 'Máximo 30 caracteres')
    .regex(CODIGO_REGEX, 'Solo minúsculas, dígitos y guion bajo; debe empezar con letra'),
  nombre: z.string().min(1, 'El nombre es requerido').max(60, 'Máximo 60 caracteres'),
  descripcion: z.string().max(250, 'Máximo 250 caracteres').optional().or(z.literal('')),
})

const updateSchema = z.object({
  nombre: z.string().min(1, 'El nombre es requerido').max(60, 'Máximo 60 caracteres'),
  descripcion: z.string().max(250, 'Máximo 250 caracteres').optional().or(z.literal('')),
  activo: z.boolean(),
})

type CreateFormValues = z.infer<typeof createSchema>
type UpdateFormValues = z.infer<typeof updateSchema>

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 === 'rol_already_exists') return data.message ?? 'El rol ya existe'
    if (data.error === 'rol_not_found') return data.message ?? 'Rol no encontrado'
    return data.message ?? data.error ?? 'Error al guardar el rol'
  }
  return 'Error al guardar el rol'
}

// ── Create Form ────────────────────────────────────────────────────────────

export function CreateRolForm({ onSuccess }: { onSuccess?: () => void }) {
  const mutation = useCreateRole()
  const form = useForm<CreateFormValues>({
    resolver: zodResolver(createSchema),
    defaultValues: { codigo: '', nombre: '', descripcion: '' },
  })

  function onSubmit(values: CreateFormValues) {
    mutation.mutate(
      {
        codigo: values.codigo,
        nombre: values.nombre,
        descripcion: values.descripcion ? values.descripcion : null,
      },
      { onSuccess: () => onSuccess?.() },
    )
  }

  const backendErr = resolveBackendError(mutation.error)

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

        <FormField
          control={form.control}
          name="codigo"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Código</FormLabel>
              <FormControl>
                <Input
                  {...field}
                  disabled={mutation.isPending}
                  placeholder="Ej: cajero_senior"
                  autoComplete="off"
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="nombre"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Nombre</FormLabel>
              <FormControl>
                <Input {...field} disabled={mutation.isPending} placeholder="Ej: Cajero Senior" />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="descripcion"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Descripción (opcional)</FormLabel>
              <FormControl>
                <Input
                  {...field}
                  disabled={mutation.isPending}
                  placeholder="Descripción del rol"
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <Button type="submit" disabled={mutation.isPending} className="w-full">
          {mutation.isPending ? 'Creando...' : 'Crear rol'}
        </Button>
      </form>
    </Form>
  )
}

// ── Edit Form ──────────────────────────────────────────────────────────────

export function EditRolForm({ initial, onSuccess }: { initial: RolDto; onSuccess?: () => void }) {
  const mutation = useUpdateRole()
  const form = useForm<UpdateFormValues>({
    resolver: zodResolver(updateSchema),
    defaultValues: {
      nombre: initial.nombre,
      descripcion: initial.descripcion ?? '',
      activo: initial.activo,
    },
  })

  function onSubmit(values: UpdateFormValues) {
    mutation.mutate(
      {
        codigo: initial.codigo,
        payload: {
          nombre: values.nombre,
          descripcion: values.descripcion ? values.descripcion : null,
          activo: values.activo,
        },
      },
      { onSuccess: () => onSuccess?.() },
    )
  }

  const backendErr = resolveBackendError(mutation.error)

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

        <FormItem>
          <FormLabel>Código</FormLabel>
          <FormControl>
            <Input value={initial.codigo} disabled readOnly />
          </FormControl>
        </FormItem>

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

        <FormField
          control={form.control}
          name="descripcion"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Descripción (opcional)</FormLabel>
              <FormControl>
                <Input {...field} disabled={mutation.isPending} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="activo"
          render={({ field }) => (
            <FormItem className="flex items-center gap-3">
              <FormControl>
                <input
                  type="checkbox"
                  checked={field.value}
                  onChange={(e) => field.onChange(e.target.checked)}
                  disabled={mutation.isPending}
                  aria-label="Activo"
                  className="h-4 w-4"
                />
              </FormControl>
              <FormLabel className="!mt-0">Activo</FormLabel>
              <FormMessage />
            </FormItem>
          )}
        />

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