import { useEffect, useRef, useState } from 'react';
import { CommunityRepository } from '@amityco/ts-sdk-react-native';
import useAuth from '../../core/hooks/useAuth';
export const useRecommendedCommunities = options => {
  const {
    limit = 4
  } = options || {};
  const {
    isConnected
  } = useAuth();
  const [communities, setCommunities] = useState();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const unsubscribersRef = useRef([]);
  const fetchRecommendedCommunities = () => {
    setLoading(true);
    return CommunityRepository.getRecommendedCommunities({
      limit: 100
    }, ({
      error,
      loading,
      data
    }) => {
      setLoading(loading);
      if (error) setError(error);
      if (!loading) {
        setCommunities(data.filter(community => !community.isJoined));
      }
    });
  };
  const unsubscribeListener = () => {
    unsubscribersRef.current.forEach(unsubscriber => unsubscriber());
    unsubscribersRef.current = [];
  };
  const refresh = () => {
    unsubscribeListener();
    setError(null);
    const unsubscribe = fetchRecommendedCommunities();
    unsubscribersRef.current.push(unsubscribe);
  };
  const onJoinCommunity = communityId => {
    setCommunities(prev => [...(prev === null || prev === void 0 ? void 0 : prev.filter(community => {
      if (community.communityId === communityId) {
        return {
          ...community,
          isJoined: true
        };
      }
      return community;
    }))]);
  };
  useEffect(() => {
    if (!isConnected) return () => {};
    const unsubscribe = fetchRecommendedCommunities();
    unsubscribersRef.current.push(unsubscribe);
    return () => unsubscribeListener();
  }, [isConnected]);
  return {
    refresh,
    onJoinCommunity,
    communities: communities === null || communities === void 0 ? void 0 : communities.slice(0, limit),
    loading,
    error
  };
};
//# sourceMappingURL=useRecommenedCommunities.js.map