import {
  useOptimisticMutation,
  useServerSuspenseQuery,
} from "@/lib/tanstack-query/hooks";
import {
  getMatchReactions,
  toggleMatchReaction,
  Reaction,
} from "@/features/matches/server";
import { PlayerInfo } from "@/features/players/types";

export const reactionKeys = {
  match: (matchId: string) => ['reactions', 'match', matchId] as const,
};

export const reactionQueries = {
  match: (matchId: string) => ({
    queryKey: reactionKeys.match(matchId),
    queryFn: () => getMatchReactions({ data: matchId }),
  }),
};

export const useMatchReactions = (matchId: string) =>
  useServerSuspenseQuery(reactionQueries.match(matchId));

const toggleReactionInList = (
  reactions: Reaction[],
  emoji: string,
  user: PlayerInfo
): Reaction[] => {
  const existing = reactions.find((reaction) => reaction.emoji === emoji);
  const hasReacted =
    existing?.players.some((player) => player.id === user.id) ?? false;

  if (hasReacted) {
    return reactions
      .map((reaction) =>
        reaction.emoji === emoji
          ? {
              ...reaction,
              count: reaction.count - 1,
              players: reaction.players.filter(
                (player) => player.id !== user.id
              ),
            }
          : reaction
      )
      .filter((reaction) => reaction.count > 0);
  }

  const optimisticPlayer: PlayerInfo = {
    id: user.id,
    first_name: user.first_name,
    last_name: user.last_name,
  };

  if (existing) {
    return reactions.map((reaction) =>
      reaction.emoji === emoji
        ? {
            ...reaction,
            count: reaction.count + 1,
            players: [...reaction.players, optimisticPlayer],
          }
        : reaction
    );
  }

  return [...reactions, { emoji, count: 1, players: [optimisticPlayer] }];
};

export const useToggleMatchReaction = (matchId: string, user?: PlayerInfo) =>
  useOptimisticMutation({
    mutationFn: toggleMatchReaction,
    queryKey: reactionKeys.match(matchId),
    optimisticUpdate: (oldData: Reaction[] | undefined, variables) => {
      if (!oldData || !user) return oldData;
      return toggleReactionInList(oldData, variables.data.emoji, user);
    },
  });
