import {useCallback, useEffect} from 'react';
import {useVisibleChatGroupInfo, visibleChatStore} from '@modules/chats/store';
import {Membership} from '@modules/chats/interfaces';

const EMPTY_MEMBERS: Membership[] = [];

export const useGroupInfo = (channel: string) => {
  const groupInfo = useVisibleChatGroupInfo();

  const updateGroupInfo = useCallback(() => {
    visibleChatStore.getState().getGroupInfo(channel);
  }, [channel]);

  /**
   * Fetch group info for the channel on first render
   */
  useEffect(() => {
    if (channel) {
      updateGroupInfo();
    }
  }, [channel, updateGroupInfo]);

  const totalMembers = groupInfo?.totalMembers || 0;
  const shortGroupMembers = groupInfo?.shortGroupMembers || EMPTY_MEMBERS;

  const useSlicedData = useCallback(
    (limit: number) => {
      return {
        shortGroupMembers: shortGroupMembers.slice(0, limit),
        isThereMoreUsers: totalMembers > limit,
      };
    },
    [shortGroupMembers, totalMembers],
  );

  return {
    totalMembers,
    shortGroupMembers,
    isUserAdmin: groupInfo?.isUserAdmin || false,
    useSlicedData,
  };
};
