import {useQuery} from 'react-query';
import {
  CALLS_QUERY_KEYS,
  MAX_CALL_PARTICIPANTS,
} from '@modules/calls/constants';
import {getLastActiveCall} from '@modules/calls/services';
import {CallStatus} from '@modules/calls/interfaces';
import {useCommunityFeature} from '@stores/communityFeatures';

import {ChatUserStatus} from '../interfaces';
import {useShallowConversation} from '../store';

export const useCallInChannel = (channel: string) => {
  const viewCallPermission = useCommunityFeature('VIEW_CALL');

  const conversation = useShallowConversation(channel, state => ({
    is_channel: !!state.is_channel,
    num_members: state.num_members,
    isConversationWithCurrentUser: state.isConversationWithCurrentUser,
    otherUserStatus: state.other_user?.status,
    otherUserDeletedAt: state.other_user?.deleted_at,
  }));

  const userUnavailable =
    conversation?.otherUserStatus === ChatUserStatus.Deactivated ||
    !!conversation?.otherUserDeletedAt;
  const isGroup = !!conversation?.is_channel;
  const isGroupCallAllowed =
    !isGroup || (conversation?.num_members ?? 0) <= MAX_CALL_PARTICIPANTS;
  const isCallEnabled =
    !!conversation &&
    viewCallPermission &&
    !conversation.isConversationWithCurrentUser &&
    isGroupCallAllowed &&
    !userUnavailable;
  const {data} = useQuery(
    CALLS_QUERY_KEYS.activeCall(channel),
    () => getLastActiveCall(channel),
    {
      enabled: isCallEnabled,
      // Polling is needed in case a socket event is missed,
      // since leaving the call isn't critical we stop polling when the call starts
      refetchInterval: d => {
        return d?.currentSession?.status === CallStatus.Active ? false : 5000;
      },
    },
  );
  const callId = data?.id;
  const externalCallId = data?.providerCallId;
  const isOngoingCall =
    isGroup && data?.currentSession?.status === CallStatus.Active;
  const isAudioCall =
    isOngoingCall && !data?.initializationConfig?.cameraEnabled;
  const isVideoCall =
    isOngoingCall && !!data?.initializationConfig?.cameraEnabled;

  return {
    callId,
    externalCallId,
    isCallEnabled,
    isOngoingCall,
    isAudioCall,
    isVideoCall,
  };
};
