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 { signupFormSchema } from "@/lib/validation/user"

type TSignupForm = z.infer<typeof signupFormSchema>

export const useSignup = () => {
	const navigate = useNavigate()
	const signup = useMutation({
		mutationKey: ["signup"],
		mutationFn: async (data: TSignupForm) => user.signup({ data }),
		onSuccess: () => {
			navigate({
				to: "/access/login"
			})
		}
	})

	const validateSignup = (formData: TSignupForm) => {
		if (!signupFormSchema.safeParse(formData).success) {
			toast.danger("Signup failed. Please check your input.")
		}
		const promise = signup.mutateAsync(formData)
		toast.promise(promise, {
			loading: "Signing up...",
			success: "Signup successful! Redirecting to login...",
			error: "Signup failed!"
		})
	}

	return {
		signup: validateSignup,
		isPending: signup.isPending
	}
}
