import React, {useEffect} from "react";
import { Navigate, Outlet, useNavigate } from "react-router-dom";
import { toast } from "react-toastify";

const AuthRoute = ({ redirectPath = "/login", children }) => {
  const isLogin = localStorage.getItem("email");
  const profile = localStorage.getItem("profile")

  const navigate = useNavigate();

  //FUNCTION TO EXPIRE SESSION AFETR 5 MINUTES
  const expireSession = () => {
    localStorage.removeItem("email");
    localStorage.removeItem('session_token');
    localStorage.removeItem('profile');
    // navigate("/login", { replace: true });
  };

  useEffect(()=>{
    setTimeout(()=>{
      expireSession()
      toast.success("Opps, session has expired", {
        icon: `🙂`,
      });
    }, 300000) //expires user login session after 5 minutes
  },[])

  if (!isLogin || !profile || (typeof JSON.parse(profile) == 'object' && JSON.parse(profile).firstname == undefined)) {
    return <Navigate to={redirectPath} replace />;
  }
  return children || <Outlet />;
};

export default AuthRoute;