import { useIsLoggedIn } from "@/lib/hooks";
import React from "react";
import { Navigate } from "react-router-dom";
import { LoadingOverlay } from "../LoadingOverlay";

type ProctectRouteProps = {
  children?: React.ReactNode;
};

export const ProtectedRoute = ({ children }: ProctectRouteProps) => {
  const { isPending, isSuccess, data: { authenticated, redirectTo } = {} } = useIsLoggedIn();

  if (isPending) {
    return <LoadingOverlay />;
  }

  if (isSuccess && !authenticated) {
    return (
      <Navigate
        to={redirectTo ?? "/login"}
        replace
        state={{
          error: "No authentication, please complete the login process.",
        }}
      />
    );
  }

  return <>{children ?? null}</>;
};
