import {useCallback, useMemo, useState} from 'react';
import {useInfiniteQuery} from 'react-query';
import {getMessageInfo} from '@modules/chats/services';

import {CHATS_QUERY_KEYS} from '../constants';
import {useGroupInfo} from './useGroupInfo';

interface Params {
  channel?: string;
  messageTs?: string;
}

export const useGetMessageInfo = ({messageTs = '', channel = ''}: Params) => {
  const {totalMembers} = useGroupInfo(channel);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const {
    data,
    isLoading,
    hasNextPage,
    fetchNextPage,
    isFetchingNextPage,
    refetch,
  } = useInfiniteQuery(
    CHATS_QUERY_KEYS.messageInfo(messageTs, channel),
    params =>
      getMessageInfo({ts: messageTs, channel, cursor: params.pageParam}),
    {
      enabled: !!messageTs && !!channel,
      getNextPageParam: lastPage =>
        lastPage && lastPage.response_metadata?.next_cursor
          ? lastPage.response_metadata.next_cursor
          : false,
      onSettled: () => {
        setIsRefreshing(false);
      },
    },
  );

  const readList = useMemo(() => {
    const pages = data
      ? data.pages.flatMap(page => page?.read_states || [])
      : [];
    return pages.filter(
      state => !!state.read_at && !!state.was_in_channel_when_message_sent,
    );
  }, [data]);

  const isPendingReads = totalMembers - 1 > readList.length;

  const getNextPage = useCallback(() => {
    if (hasNextPage) {
      fetchNextPage();
    }
  }, [fetchNextPage, hasNextPage]);

  const refresh = useCallback(() => {
    setIsRefreshing(true);
    refetch();
  }, [refetch]);

  return {
    readList,
    isLoading,
    isFetchingNextPage,
    getNextPage,
    /**
     * totalMembers except current user
     */
    totalMembers: totalMembers - 1,
    /**
     * Total members that have not read the message yet
     */
    isPendingReads,
    refresh,
    isRefreshing,
  };
};
