import { Loader } from "components/Loader/Loader";
import { Navigate, useParams } from "react-router-dom";
import { useAppSelector } from "redux/hooks";

export const PrivateRoute = ({
  children,
}: // permission,
{
  children: JSX.Element;
  permission?: string;
}) => {
  const { token, loading } = useAppSelector((state) => state.auth);
  const { subdomain } = useParams();

  // const { data: user, isLoading: loadingUser } = useGetSignedUserInfoQuery();

  // useEffect(() => {
  //   if (user) dispatch(setUser(user));
  // }, [dispatch, user]);

  if (loading) {
    return <Loader />;
  }

  // let newPermissions: any[] = [];
  // // aggregate the rules from multi
  // user?.roles?.forEach(
  //   (r) => (newPermissions = [...newPermissions, ...r.permissions])
  // );

  // const userHasRequiredPermission = permission
  //   ? !!newPermissions.find((p) => p.name === permission)
  //   : true;

  console.log(token);
  

  if (!token) {
    return <Navigate to={`/${subdomain}/login`} />;
  }

  // if (token && !userHasRequiredPermission) {
  //   return <AccessDenied />; // build your won access denied page (sth like 404)
  // }

  return children;
};
