import { useMutation } from 'react-query';

import { logEvent } from 'src/config/logging';
import { useAuth } from 'src/contexts/JWTContext';
import {
  addAcknowledgementReaction,
  removeAcknowledgementReaction,
} from 'src/pages/dashboard/acknowledgements/services';
import { type Acknowledgement } from 'src/pages/dashboard/acknowledgements/types';
import {
  addUserAcknowledgementListDataReaction,
  removeUserAcknowledgementListDataReaction,
} from 'src/pages/dashboard/profile/queries';
import { EventName } from 'src/types/amplitude';
import { canAddReaction } from 'src/utils/reactions';

type ReactionsMutationProps = Pick<Acknowledgement, 'id' | 'reactions'>;

const useReactionsMutation = ({ id, reactions }: ReactionsMutationProps) => {
  const { user: loggedUser } = useAuth();

  const addReactionMutation = useMutation(
    ({ emoji, unified }: { emoji: string; unified: string }) => {
      if (!canAddReaction(reactions, emoji))
        throw new Error('Reaction not allowed');
      return addAcknowledgementReaction(id, emoji, unified);
    },
    {
      onSuccess: (_, { emoji, unified }) => {
        logEvent(EventName.ACKNOW_REACTION, {
          acknowledgementId: id,
          reaction: emoji,
        });

        if (!loggedUser?.id) throw new Error('User not found');

        addUserAcknowledgementListDataReaction(
          loggedUser.id,
          id,
          emoji,
          unified,
        );
      },
    },
  );
  const removeReactionMutation = useMutation(
    (emoji: string) => removeAcknowledgementReaction(id, emoji),
    {
      onSuccess: (_, emoji) => {
        if (!loggedUser?.id) throw new Error('User not found');
        removeUserAcknowledgementListDataReaction(loggedUser.id, id, emoji);
      },
    },
  );

  const handleAddReaction = (emoji: string, unified: string) =>
    addReactionMutation.mutate({ emoji, unified });

  const handleRemoveReaction = (emoji: string) =>
    removeReactionMutation.mutate(emoji);

  return {
    removeReactionMutation,
    addReactionMutation,
    handleAddReaction,
    handleRemoveReaction,
  };
};

export default useReactionsMutation;
