import { useEffect, useMemo } from 'react';

import { logEvent } from 'src/config/amplitude';
import {
  type MessageReaction,
  type SummaryReaction,
} from 'src/pages/dashboard/Conversations/types';
import { EventName } from 'src/types/amplitude';
import { getFullName } from 'src/utils/userUtils';

import { getConversationInfo } from '../queries';
import { fetchMissingMembers, useMembersStore } from '../stores/membersStore';

export const useReactionsWithUsers = (
  reactions: MessageReaction[] | undefined,
  channelId: string | undefined,
): SummaryReaction[] => {
  const { members } = useMembersStore();

  // Memoized so the ID list doesn't recompute on every members store update
  const reactionUserIds = useMemo(
    () => [
      ...new Set(
        (reactions ?? [])
          .filter(r => Array.isArray(r.users))
          .flatMap(r => r.users),
      ),
    ],
    [reactions],
  );

  const reactionsWithUsers = useMemo<SummaryReaction[]>(() => {
    if (!reactions?.length) return [];

    return reactions
      .filter(r => Array.isArray(r.users))
      .map(reaction => ({
        ...reaction,
        users: reaction.users
          .map(userId => {
            const member = members[userId];
            if (!member) return null;
            return {
              name: getFullName({
                firstName: member.first_name,
                lastName: member.last_name,
              }),
              id: member.id,
              picture: member.picture_asset_url || '',
              emoji: reaction.name,
            };
          })
          .filter((user): user is NonNullable<typeof user> => Boolean(user)),
      }));
  }, [reactions, members]);

  useEffect(() => {
    if (!reactionUserIds.length || !channelId) return;

    const missingUserIds = reactionUserIds.filter(id => !members[id]);
    if (!missingUserIds.length) return;

    const newlySubmitted = fetchMissingMembers(missingUserIds);
    if (newlySubmitted.length) {
      logEvent(EventName.CHATS_2_REACTION_USERS_NOT_IN_MEMBERS, {
        channelId,
        conversationType:
          (getConversationInfo(channelId)?.is_channel ?? false)
            ? 'group'
            : 'individual',
        memberIds: Object.keys(members),
        missingUserIds: newlySubmitted,
      });
    }
  }, [reactionUserIds, channelId, members]);

  return reactionsWithUsers;
};
