import { useEffect, useState } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { useEstablishment } from '@/context/EstablishmentContext';
import { FE_USERS_LOGIN_URL, getRedirectUrlFromRole } from '@/utils/Url';
import Loader from '@/components/Loader';
import logger from '@/utils/logger';

const ProtectedRoute = ({ children, requiredRight }) => {
  const { data: session, status } = useSession();
  const { profileRole } = useEstablishment();
  const router = useRouter();
  const [hasRequiredRight, setHasRequiredRight] = useState(false);

  useEffect(() => {
    // Ne pas agir tant que NextAuth charge la session
    if (status === 'loading') return;

    logger.debug({ status, profileRole, requiredRight });

    if (status === 'unauthenticated') {
      router.push(FE_USERS_LOGIN_URL);
      return;
    }

    // status === 'authenticated' — vérifier les droits
    if (profileRole !== null && profileRole !== undefined) {
      let requiredRightChecked = false;
      if (requiredRight && Array.isArray(requiredRight)) {
        requiredRightChecked = requiredRight.some(
          (right) => profileRole === right
        );
      } else {
        requiredRightChecked = profileRole === requiredRight;
      }
      setHasRequiredRight(requiredRightChecked);

      if (!requiredRightChecked) {
        const redirectUrl = getRedirectUrlFromRole(profileRole);
        if (redirectUrl) {
          router.push(redirectUrl);
        }
      }
    }
  }, [status, profileRole, requiredRight]);

  if (status === 'loading' || !hasRequiredRight) return <Loader />;

  return children;
};

export default ProtectedRoute;
