import { useEffect } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
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 { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { useUser } from '../hooks/useUser'
import { useUpdateUser } from '../hooks/useUpdateUser'
import { ResetPasswordModal } from '../components/ResetPasswordModal'
import { PermisosEditor } from '../components/PermisosEditor'
import { useAuthStore } from '@/stores/authStore'

const editSchema = z.object({
  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'),
  activo: z.boolean(),
})

type EditFormValues = z.infer<typeof editSchema>

function resolveBackendError(err: unknown): string | null {
  if (!err) return null
  if (isAxiosError(err) && err.response?.data) {
    const data = err.response.data as { title?: string; error?: string; message?: string }
    if (data.title === 'last-admin-lockout' || data.error === 'last-admin-lockout') {
      return 'No podés cambiar el rol o desactivar al último administrador activo'
    }
    return data.message ?? data.error ?? 'Error al actualizar el usuario'
  }
  return 'Error al actualizar el usuario'
}

export function UserEditPage() {
  const { id } = useParams<{ id: string }>()
  const userId = Number(id)
  const navigate = useNavigate()
  const loggedUserId = useAuthStore((s) => s.user?.id)

  const { data: user, isLoading } = useUser(userId)
  const { mutate, isPending, error } = useUpdateUser(userId)

  const form = useForm<EditFormValues>({
    resolver: zodResolver(editSchema),
    defaultValues: {
      nombre: '',
      apellido: '',
      email: '',
      rol: '',
      activo: true,
    },
  })

  // Prefill form when user data loads
  useEffect(() => {
    if (user) {
      form.reset({
        nombre: user.nombre,
        apellido: user.apellido,
        email: user.email ?? '',
        rol: user.rol,
        activo: user.activo,
      })
    }
  }, [user, form])

  function handleSubmit(values: EditFormValues) {
    mutate(
      {
        nombre: values.nombre,
        apellido: values.apellido,
        email: values.email || null,
        rol: values.rol,
        activo: values.activo,
      },
      {
        onSuccess: () => {
          navigate('/usuarios')
        },
      },
    )
  }

  const backendError = resolveBackendError(error)

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <span className="text-muted-foreground">Cargando...</span>
      </div>
    )
  }

  if (!user) {
    return (
      <div className="py-12 text-center text-muted-foreground">
        Usuario no encontrado.
      </div>
    )
  }

  const isSelf = loggedUserId === userId

  return (
    <div className="max-w-xl space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-semibold">Editar Usuario</h1>
        <div className="flex items-center gap-2">
          {!isSelf && <ResetPasswordModal userId={userId} />}
          <Button variant="ghost" size="sm" onClick={() => navigate('/usuarios')}>
            Volver
          </Button>
        </div>
      </div>

      {/* Username — display only, not editable */}
      <div className="space-y-1">
        <p className="text-sm font-medium text-muted-foreground">Usuario</p>
        <p className="text-sm font-mono bg-muted rounded px-3 py-2">{user.username}</p>
      </div>

      <Tabs defaultValue="perfil">
        <TabsList>
          <TabsTrigger value="perfil">Perfil</TabsTrigger>
          <TabsTrigger value="permisos" disabled={isSelf}>
            Permisos
          </TabsTrigger>
        </TabsList>

        <TabsContent value="perfil">
          <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>
              )}

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

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

              <FormField
                control={form.control}
                name="email"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Email (opcional)</FormLabel>
                    <FormControl>
                      <Input {...field} type="email" disabled={isPending} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="rol"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Rol</FormLabel>
                    <Select
                      value={field.value}
                      onValueChange={field.onChange}
                      disabled={isPending}
                    >
                      <FormControl>
                        <SelectTrigger className="w-full" aria-label="Rol">
                          <SelectValue placeholder="Seleccioná un rol" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value="admin">Admin</SelectItem>
                        <SelectItem value="cajero">Cajero</SelectItem>
                        <SelectItem value="reportes">Reportes</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

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

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

        <TabsContent value="permisos">
          <PermisosEditor userId={userId} />
        </TabsContent>
      </Tabs>
    </div>
  )
}
