import {
  type FC,
  type PropsWithChildren,
  type ReactElement,
  useState,
} from 'react';
import { Navigate, useLocation } from 'react-router-dom';

import useAuth from 'src/contexts/JWTContext';

import Login from '../pages/authentication/Login';

const AuthGuard: FC<PropsWithChildren> = ({ children }) => {
  const auth = useAuth();
  const location = useLocation();
  const [requestedLocation, setRequestedLocation] = useState<string | null>(
    null,
  );

  if (!auth.isAuthenticated) {
    if (location.pathname !== requestedLocation) {
      setRequestedLocation(location.pathname);
    }

    return <Login />;
  }

  // This is done so that in case the route changes by any chance through other
  // means between the moment of request and the render we navigate to the initially
  // requested route.
  if (requestedLocation && location.pathname !== requestedLocation) {
    setRequestedLocation(null);
    return <Navigate to={requestedLocation} />;
  }

  return children as ReactElement;
};

export default AuthGuard;
