import ErrorPage from "@components/ErrorPage";
import React, { useEffect } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";

type AuthProps = {
    children: React.ReactNode,
}
export default function AuthComponent({ children }: AuthProps) {
    const navigate = useNavigate();
    const searchParams = useSearchParams()[0];
    const isLogged = searchParams.has("logged");

    useEffect(() => {
        // navigate needs to be wrapped in a useEffect so that it gets executed after the component is mounted. Otherwise it doesn't redirect
        if (!isLogged)
            navigate("/login", { replace: true });
    }, [isLogged])

    if (isLogged)
        return <>{children}</>;
    // else
    // return <ErrorPage err={new Error("You are not logged in and you should have been redirected to the login page. Something went wrong.")}/>;
}