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

function WithAuthMiddleware({ children }) {
  const router = useRouter();
  const pathName = usePathname();
  const { isAuth, initAuthState, errorState } = useAuth();

  useEffect(() => {
    if (!initAuthState) return;
    if (!isAuth) {
      router.replace(`/login?redirect=${encodeURIComponent(pathName)}`);
    }
  }, [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 WithAuthMiddleware;
