import { ErrorOverlay, LoadingOverlay } from "@/components";
import { useGetProfile, useIsLoggedIn } from "@/lib/hooks";
import React, { useId } from "react";
import { Navigate, useLocation } from "react-router-dom";

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

export const ProtectedRoute = ({ children }: ProctectRouteProps) => {
  const location = useLocation();
  //const { i18n } = useTranslation();
  const id = useId();

  const {
    isSuccess: isLoggedInSuccess,
    isLoading: isLoggedInLoading,
    data: { authenticated = false, redirectTo = "/login" } = {},
  } = useIsLoggedIn();

  const {
    isSuccess: isProfileSuccess,
    isLoading: isProfileLoading,
    error: profileError,
    data: profile,
  } = useGetProfile({
    enabled: isLoggedInSuccess && authenticated,
  });

  // Cambiamos el idioma de la aplicación si es necesario
  /*React.useEffect(() => {
    if (isProfileSuccess && profile?.lang_code && i18n.language !== profile.lang_code) {
      i18n.changeLanguage(profile.lang_code);
    }
  }, [isProfileSuccess, profile?.lang_code, i18n]);*/

  if (isLoggedInLoading || isProfileLoading) {
    return <LoadingOverlay />;
  }

  if (profileError) {
    console.error("Error loading profile:", profileError);
    return <ErrorOverlay subtitle={(profileError as Error).message} />;
  }

  // Redirección si el usuario no está autenticado
  if ((isLoggedInSuccess && !authenticated) || (isProfileSuccess && !profile?.id)) {
    return <Navigate to={redirectTo} state={{ from: location }} replace />;
  }

  // Renderizamos los hijos si el usuario está autenticado
  return <div id={`${id}-${profile?.lang_code}`}>{children ?? null}</div>;
};
