import React, { useEffect, useState } from "react";
import { Navigate, useLocation } from "react-router-dom";
import Layout from "../layouts/Layout";
import {
  getRoleIdsFromToken,
  ROLE_SUPPORT_ID,
  isTicketRoute,
} from "../../utils/authUtils";
import {
  consumeTokenFromUrl,
  isAuthenticated,
  redirectToHseLogin,
} from "hse-auth";

const ProtectedRoute = ({ children, noLayout = false }) => {
  const location = useLocation();
  const [authReady, setAuthReady] = useState(false);

  useEffect(() => {
    let cancelled = false;

    (async () => {
      await consumeTokenFromUrl();
      if (!cancelled) {
        setAuthReady(true);
      }
    })();

    return () => {
      cancelled = true;
    };
  }, [location.search]);

  if (!authReady) {
    return <div>Loading session...</div>;
  }

  if (!isAuthenticated()) {
    redirectToHseLogin();
    return <div>Redirecting to HSE sign-in...</div>;
  }

  const roleIds = getRoleIdsFromToken();
  const supportOnly = roleIds.length === 1 && roleIds.includes(ROLE_SUPPORT_ID);
  if (!noLayout && supportOnly && !isTicketRoute(location.pathname)) {
    return <Navigate to="/tickets" replace />;
  }

  if (noLayout) {
    return <>{children}</>;
  }
  return <Layout>{children}</Layout>;
};

export default ProtectedRoute;
