import { useEffect } from 'react';

import { queryClient } from 'src/config/react-query';
import { EVENTS_SOCKETS } from 'src/constants/sockets';
import { type SocketContextValue } from 'src/contexts/SocketContext';
import {
  type State,
  type Task,
} from 'src/pages/dashboard/serviceManagement/types';

import { serviceManagementKeys } from '../queries';

type TaskStateListUpdaterParams = {
  socket: SocketContextValue;
  params: Record<string, any>;
};

type TaskStateUpdateSocketData = {
  taskId: string;
  newState: State;
};

const useTaskStateListUpdater = ({
  socket,
  params,
}: TaskStateListUpdaterParams) => {
  useEffect(() => {
    const handleNewState = (data: TaskStateUpdateSocketData) => {
      if (!data) return;

      queryClient.setQueryData(
        serviceManagementKeys.tasks.list(params),
        (oldData: any) => {
          if (!oldData) return oldData;

          const updateTask = (task: Task) =>
            task.id === data.taskId ? { ...task, state: data.newState } : task;

          if (Array.isArray(oldData?.pages)) {
            return {
              ...oldData,
              pages: oldData.pages.map((page: any) => ({
                ...page,
                data: {
                  ...page.data,
                  items: page.data?.items?.map(updateTask) ?? page.data?.items,
                },
              })),
            };
          }

          return {
            ...oldData,
            data: {
              ...oldData?.data,
              items:
                oldData?.data?.items?.map(updateTask) ?? oldData?.data?.items,
            },
          };
        },
      );
    };

    socket.listenEvent(
      EVENTS_SOCKETS.SERVICE_MANAGER_TASK_NEW_STATE,
      handleNewState,
    );

    return () => {
      socket.closeEvent(
        EVENTS_SOCKETS.SERVICE_MANAGER_TASK_NEW_STATE,
        handleNewState,
      );
    };
  }, [socket, params]);
};

export default useTaskStateListUpdater;
