import { toast } from "@heroui/react"
import { useMutation } from "@tanstack/react-query"
import { useNavigate } from "@tanstack/react-router"
import type z from "zod"
import { user } from "@/lib/server/user"
import { loginFormSchema } from "../validation/user"

type TLoginForm = z.infer<typeof loginFormSchema>

export const useLogin = () => {
	const navigate = useNavigate()

	const loginMutation = useMutation({
		mutationKey: ["login"],
		mutationFn: async (data: TLoginForm) => {
			const response = await user.login({ data })
			if (response.error) {
				throw new Error(response.message)
			}
		},
		onSuccess: () => {
			navigate({
				to: "/"
			})
		}
	})

	const validateLogin = (formData: TLoginForm) => {
		if (!loginFormSchema.safeParse(formData).success) {
			toast.danger("Error en el formulario.")
			return false
		}
		const promise = loginMutation.mutateAsync(formData)

		toast.promise(promise, {
			loading: "Logging in...",
			success: "Login successful! Redirecting to posts..",
			error: (error) => error.message
		})
	}

	return {
		login: validateLogin,
		isPending: loginMutation.isPending
	}
}
