import { TextUtil } from "@greatness/util";
import { useEffect } from "react";
import { Navigate, useNavigate } from "react-router-dom";

import { useSessionContext } from "@/components/SessionContext";
import { NavigationPath } from "@/constants/navigation";

export default function PrivateRoute({
  Component,
  redirectTo,
}: {
  Component?: React.FC;
  redirectTo?: string;
}) {
  const navigate = useNavigate();
  const { isAuthenticated } = useSessionContext();

  useEffect(() => {
    if (!isAuthenticated) {
      // eslint-disable-next-line @typescript-eslint/no-floating-promises
      navigate(NavigationPath.Login);
    }
  }, [navigate, isAuthenticated]);

  if (isAuthenticated) {
    if (!TextUtil.isEmpty(redirectTo)) {
      return <Navigate to={redirectTo!} />;
    }
    return Component ? <Component /> : null;
  }
  return null;
}
