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 { useCreateUser } from '../hooks/useCreateUser'
import { useRolesForSelect } from '../hooks/useRolesForSelect'
import type { CreatedUserDto } from '../api/createUser'

const userFormSchema = z.object({
  username: z
    .string()
    .min(3, 'Mínimo 3 caracteres')
    .max(50, 'Máximo 50 caracteres'),
  password: z
    .string()
    .min(8, 'Mínimo 8 caracteres')
    .regex(/[a-zA-Z]/, 'Debe contener al menos una letra')
    .regex(/[0-9]/, 'Debe contener al menos un dígito'),
  nombre: z.string().min(1, 'El nombre es requerido'),
  apellido: z.string().min(1, 'El apellido es requerido'),
  email: z.string().email('Email inválido').optional().or(z.literal('')),
  rol: z.string().min(1, 'Seleccioná un rol válido'),
})

type UserFormValues = z.infer<typeof userFormSchema>

interface UserFormProps {
  onSuccess?: (user: CreatedUserDto) => 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 === 'username_taken') {
      return data.message ?? 'El usuario ya existe'
    }
    return data.error ?? 'Error al crear el usuario'
  }
  return 'Error al crear el usuario'
}

export function UserForm({ onSuccess }: UserFormProps) {
  const { mutate, isPending, error } = useCreateUser()
  const { options: rolOptions, isLoading: rolesLoading, isError: rolesError } = useRolesForSelect()

  const form = useForm<UserFormValues>({
    resolver: zodResolver(userFormSchema),
    defaultValues: {
      username: '',
      password: '',
      nombre: '',
      apellido: '',
      email: '',
      rol: '',
    },
  })

  function handleSubmit(values: UserFormValues) {
    mutate(
      {
        username: values.username,
        password: values.password,
        nombre: values.nombre,
        apellido: values.apellido,
        email: values.email || undefined,
        rol: values.rol,
      },
      {
        onSuccess: (data) => {
          onSuccess?.(data)
        },
      },
    )
  }

  const backendError = resolveBackendError(error)
  const disabled = isPending || rolesLoading

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

        {rolesError && (
          <Alert variant="destructive">
            <AlertCircle className="h-4 w-4" />
            <AlertDescription>
              No se pudieron cargar los roles. Intentá refrescar la página.
            </AlertDescription>
          </Alert>
        )}

        <FormField
          control={form.control}
          name="username"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Usuario</FormLabel>
              <FormControl>
                <Input
                  {...field}
                  type="text"
                  autoComplete="off"
                  disabled={disabled}
                  placeholder="Nombre de usuario"
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="password"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Contraseña</FormLabel>
              <FormControl>
                <Input
                  {...field}
                  type="password"
                  autoComplete="new-password"
                  disabled={disabled}
                  placeholder="Mínimo 8 chars, letra y dígito"
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

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

        <FormField
          control={form.control}
          name="apellido"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Apellido</FormLabel>
              <FormControl>
                <Input {...field} type="text" disabled={disabled} placeholder="Apellido" />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="email"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Email (opcional)</FormLabel>
              <FormControl>
                <Input
                  {...field}
                  type="email"
                  autoComplete="off"
                  disabled={disabled}
                  placeholder="correo@ejemplo.com"
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="rol"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Rol</FormLabel>
              <Select
                value={field.value}
                onValueChange={field.onChange}
                disabled={disabled || !!rolesError}
              >
                <FormControl>
                  <SelectTrigger className="w-full" aria-label="Rol">
                    <SelectValue
                      placeholder={rolesLoading ? 'Cargando roles...' : 'Seleccioná un rol'}
                    />
                  </SelectTrigger>
                </FormControl>
                <SelectContent>
                  {rolOptions.map((r) => (
                    <SelectItem key={r.codigo} value={r.codigo}>
                      {r.nombre}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <FormMessage />
            </FormItem>
          )}
        />

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