import { useEffect } from 'react';

import { EVENTS_SOCKETS } from 'src/constants/sockets';
import { useAuth } from 'src/contexts/JWTContext';
import { useSocket } from 'src/contexts/SocketContext';
import { type AcknowledgementReactionSocket } from 'src/pages/dashboard/acknowledgements/types';

import {
  addAcknowledgementListDataReaction,
  removeAcknowledgementListDataReaction,
} from '../queries';

const { NEW_ACKNOWLEDGMENT_REACTION, REMOVE_ACKNOWLEDGMENT_REACTION } =
  EVENTS_SOCKETS;

const useReactionsSocket = () => {
  const socket = useSocket();
  const { user } = useAuth();

  useEffect(() => {
    // Handler functions for socket events
    const eventHandlers = {
      // Add a new reaction to an acknowledgement
      addAcknowledgementReaction: (reaction: AcknowledgementReactionSocket) => {
        const { emoji, unified, userId, acknowledgmentId } = reaction;

        addAcknowledgementListDataReaction(
          acknowledgmentId,
          emoji,
          unified,
          userId === user?.id,
        );
      },

      // Remove a reaction from an acknowledgement
      removeAcknowledgementReaction: (
        reaction: AcknowledgementReactionSocket,
      ) => {
        const { emoji, userId, acknowledgmentId } = reaction;

        removeAcknowledgementListDataReaction(
          acknowledgmentId,
          emoji,
          userId === user?.id,
        );
      },
    };

    // Map of event names to their handlers
    const eventSubscriptions = {
      [NEW_ACKNOWLEDGMENT_REACTION]: eventHandlers.addAcknowledgementReaction,
      [REMOVE_ACKNOWLEDGMENT_REACTION]:
        eventHandlers.removeAcknowledgementReaction,
    };

    // Subscribe to all events
    Object.entries(eventSubscriptions).forEach(([event, handler]) => {
      socket.listenEvent(event, handler);
    });

    // Cleanup function to unsubscribe from all events
    return () => {
      Object.entries(eventSubscriptions).forEach(([event, handler]) => {
        socket.closeEvent(event, handler);
      });
    };
  }, [socket, user?.id]);
};

export default useReactionsSocket;
