import {useMemo, useRef} from 'react';
import {useConversations} from '@modules/chats/store';
import {ChatUserStatus, Conversation} from '@modules/chats/interfaces';

interface Params {
  searchText: string;
  /**
   * If true, the conversations will not be subscribed to the store or to the new searchText param results.
   * This is useful to avoid re-ordering the conversations list when a message is forwarded to a bunch of conversations.
   */
  freeze?: boolean;
  withoutDeactivatedUsers?: boolean;
}

export const useSearchConversations = ({
  searchText,
  freeze = false,
  withoutDeactivatedUsers,
}: Params) => {
  const rawConversations = useConversations();
  const frozenConversationsRef = useRef<Conversation[]>(rawConversations);

  // Update frozen conversations only when not frozen
  if (!freeze) {
    frozenConversationsRef.current = rawConversations;
  }

  const targetConversations = freeze
    ? frozenConversationsRef.current
    : rawConversations;

  const filtered = useMemo(() => {
    const conversations: Conversation[] = [];

    for (const conversation of targetConversations) {
      const groupName = conversation.name?.toLowerCase();
      const otherUserName = `${conversation.other_user?.first_name ?? ''} ${
        conversation.other_user?.last_name ?? ''
      }`.toLowerCase();

      const userStatus = conversation.other_user?.status;
      // Check first a user status if needed before searching in text
      if (
        withoutDeactivatedUsers &&
        (userStatus === ChatUserStatus.Deactivated ||
          userStatus === ChatUserStatus.Deleted)
      ) {
        continue;
      }

      if (
        !searchText ||
        groupName?.includes(searchText.toLowerCase()) ||
        otherUserName?.includes(searchText.toLowerCase())
      ) {
        conversations.push(conversation);
      }
    }

    return conversations;
  }, [targetConversations, searchText, withoutDeactivatedUsers]);

  return filtered;
};
