"use client";
import { useAuth } from "@/lib/contexts/auth";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect } from "react";
import LoadingHardPage from "../components/LoadingHardPage";
import { Stack, Typography } from "@mui/material";

function WithoutAuthMiddleware({ children }) {
  const router = useRouter();
  const { isAuth, initAuthState, errorState } = useAuth();
  const searchParams = useSearchParams();

  const redirect = searchParams.get("redirect");

  useEffect(() => {
    if (!initAuthState) return;
    if (isAuth) {
      router.replace(redirect ? decodeURIComponent(redirect) : "/dashboard");
    }
  }, [isAuth, initAuthState]);

  if (!initAuthState || isAuth)
    return (
      <LoadingHardPage
        authState={errorState.status}
        label={
          errorState.status ? (
            <Stack justifyContent={"center"} alignItems={"center"}>
              <Typography variant={"body1"}>{errorState.message}</Typography>
              <Typography variant={"body1"}>
                {" "}
                کد : {errorState.status}
              </Typography>
            </Stack>
          ) : (
            <Typography variant={"body1"}>درحال احراز هویت...</Typography>
          )
        }
        loading={true}
      />
    );
  return <>{children}</>;
}

export default WithoutAuthMiddleware;
