import { useGetProfile, useIsLoggedIn } from "@/lib/hooks";
import React, { useEffect } from "react";
import { useTranslation } from "react-i18next";
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();
  const { data: profile, ...profileStatus } = useGetProfile();
  const { i18n } = useTranslation();

  useEffect(() => {
    if (profileStatus.isSuccess && i18n.language !== profile?.lang_code) {
      i18n.changeLanguage(profile?.lang_code);
    }
  }, [profile, profileStatus, i18n]);

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

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

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