import { useEffect, useState } from "react";
import { Navigate, Outlet, useLocation, useNavigate } from "react-router-dom";

const AuthRoute = ({ redirectPath = "/login", children }) => {
  const [lastActivityTime, setLastActivityTime] = useState(Date.now());
  const isLogin = localStorage.getItem("email");

  const navigate = useNavigate();
  const { pathname } = useLocation();


  //Removing Data stored at localStorage after session expires
  const expireSession = () => {
    localStorage.removeItem("email");
    localStorage.removeItem('session_token');
    localStorage.removeItem('firstname');
    localStorage.removeItem('member_id');
    localStorage.removeItem('lastname');
    localStorage.removeItem('state');
    localStorage.removeItem('last_login');
    localStorage.removeItem('uid');
    localStorage.removeItem('session');
    localStorage.removeItem('city');
    localStorage.removeItem('country');
    localStorage.removeItem('loglevel');
    localStorage.removeItem('zip_code');
    localStorage.removeItem('added');
    navigate("/login", { replace: true }); // redirects user to login page after session expires
  };

  const checkInactivity = setInterval(() => {
    if (Date.now() - lastActivityTime > process.env.REACT_APP_SESSION_EXPIRE_MINUTES) {
      expireSession()
    }
  }, process.env.REACT_APP_SESSION_EXPIRE_CHECKER) // Checks for inactivity every minute

  // Reset last activity time on user input
  const resetTime = () => {
    setLastActivityTime(Date.now());
  }
  window.addEventListener('mousemove', resetTime)
  window.addEventListener('keydown', resetTime)

  useEffect(() => {
    // cleaning up listeners
    return () => {
      clearInterval(checkInactivity)
      window.removeEventListener('mousemove', resetTime)
      window.removeEventListener('keydown', resetTime)
    }
  }, [pathname, lastActivityTime])

  if (!isLogin) {
    return <Navigate to={redirectPath} replace />;
  }
  return children || <Outlet />;
};

export default AuthRoute;
