import type { Models } from "@nontara/server/models";
import { useMutation } from "@tanstack/react-query";
import { useEffect, useEffectEvent } from "react";
import { useNavigate } from "react-router";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { apiClient } from "@/lib/api";

export default function IndexPage() {
	const navigate = useNavigate();
	const { mutate: mutateOnboardStatus, isPending } = useMutation({
		mutationFn: async () => {
			const response =
				await apiClient.get<Models.OnboardStatusOutput>("onboard/status");
			return await response.json();
		},
		onSuccess(data) {
			if (data.needsOnboarding) {
				navigate("/onboard");
				const preloader = document.getElementById("preloader");
				if (preloader) {
					preloader.classList.add("hidden");
				}
			}
		},
		retry: 1,
	});
	const onOnboardCheckingStatus = useEffectEvent(() => {
		// Hide preloader after React has rendered
		const accountStorage = localStorage.getItem("account");
		if (!accountStorage) {
			mutateOnboardStatus();
		}
	});
	useEffect(() => {
		onOnboardCheckingStatus();
	}, []);
	if (isPending) return;
	return (
		<>
			<span>{JSON.stringify(import.meta.env)}</span>
			<Button
				onClick={() => {
					toast("This is Toast");
				}}
			>
				Show Toast
			</Button>
		</>
	);
}
