import useUser from "@/lib/app/hooks/useUser";
import {useRouter} from "next/router";
import {useEffect} from "react";
import WithoutAuthComponent from "@/core/components/Middleware/WithoutAuthComponent";

const WithoutAuthMiddleware = ({children}) => {
    const {isAuth} = useUser();
    const router = useRouter();

    const backUrlDecodedPath = router.query?.back_url;

    useEffect(() => {
        if (!isAuth) return;
        const timer = setTimeout(() => {
            router.replace(
                backUrlDecodedPath
                    ? decodeURIComponent(backUrlDecodedPath)
                    : "/dashboard"
            );
        }, 2000);

        return () => {
            clearTimeout(timer);
        };
    }, [isAuth]);

    return isAuth ? (
        <WithoutAuthComponent  backUrlDecodedPath={backUrlDecodedPath} />
    ) : (
        <>{children}</>
    );
};

export default WithoutAuthMiddleware;
