import { useEffect } from 'react';

import { EVENTS_SOCKETS } from 'src/constants/sockets';
import { useSocket } from 'src/contexts/SocketContext';
import {
  type Acknowledgement,
  type Category,
} from 'src/pages/dashboard/acknowledgements/types';

import {
  addAcknowledgementInListAcknowledgements,
  removeAcknowledgement,
  updateAcknowledgementById,
  updateAcknowledgementListCategoryData,
  updateCategoryListData,
} from '../queries';

const {
  ACKNOWLEDGEMENT_CATEGORY_UPDATED,
  ACKNOWLEDGEMENT_CREATED,
  ACKNOWLEDGEMENT_UPDATED,
  ACKNOWLEDGEMENT_DELETED,
} = EVENTS_SOCKETS;

const useAcknowledgementSocket = () => {
  const socket = useSocket();

  useEffect(() => {
    // Handler functions for socket events
    const eventHandlers = {
      // Update category data in both category list and acknowledgement list
      updateCategory: (category: Category) => {
        updateAcknowledgementListCategoryData(category);
        updateCategoryListData(category);
      },

      // Add new acknowledgement to the list
      acknowledgementCreated: (acknowledgement: Acknowledgement) => {
        addAcknowledgementInListAcknowledgements(acknowledgement);
      },

      // Update existing acknowledgement
      acknowledgementUpdated: (acknowledgement: Acknowledgement) => {
        updateAcknowledgementById(acknowledgement);
      },

      // Remove acknowledgement from the list
      acknowledgementDeleted: (acknowledgement: Acknowledgement) => {
        removeAcknowledgement(acknowledgement.id);
      },
    };

    // Map of event names to their handlers
    const eventSubscriptions = {
      [ACKNOWLEDGEMENT_CATEGORY_UPDATED]: eventHandlers.updateCategory,
      [ACKNOWLEDGEMENT_CREATED]: eventHandlers.acknowledgementCreated,
      [ACKNOWLEDGEMENT_UPDATED]: eventHandlers.acknowledgementUpdated,
      [ACKNOWLEDGEMENT_DELETED]: eventHandlers.acknowledgementDeleted,
    };

    // 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]);
};

export default useAcknowledgementSocket;
