import { useDispatch } from "react-redux";
import { useCallback } from "react";
import { CurrentConversationType } from "../types/ChatListType";
import { useAppSelector } from "../utils/hooks";
import { updateMessageOptions } from "../store/Slices/MessageOptionsSlice";
import { updateCurrentConversation } from "../store/Slices/CurrentConversationSlice";
import { updateUnreadCountByChatId } from "../store/Slices/ChatListSlice";
import { removeMessageList } from "../store/Slices/MessageListSlice";
import { updateSearchMessageResult } from "../store/Slices/SearchMessageSlice";
import { updateViewState } from "../store/Slices/ViewManagerSlice";
import { updateSendMessageData } from "../store/Slices/SendMessageSlice";
import { useFile } from "../context/FileProvider";
import { socketInstance } from "../socket/socket";

export const useNavigateToChat = () => {
  const dispatch = useDispatch();
  const { setSelectedFile } = useFile();
  const currentConversationData = useAppSelector(
    (state) => state.CurrentConversation,
  );

  const navigateToChat = useCallback(
    (data: CurrentConversationType) => {
      if (
        currentConversationData.chat_id != data.chat_id ||
        currentConversationData.chat_id == 0 ||
        currentConversationData.chat_id == -1
      ) {
        socketInstance().emit("typing", {
          chat_id: currentConversationData.chat_id,
          typing: false,
        });

        dispatch(
          updateMessageOptions({
            show_forward_message_modal: false,
            selectMessage: false,
            forward_message: false,
            currentPage: "1",
            message_list: {
              Records: [],
              Pagination: {
                total_pages: 0,
                total_records: 0,
                current_page: 0,
                records_per_page: 0,
              },
            },
          }),
        );

        data.is_conversation_changed = Math.random();

        dispatch(updateCurrentConversation(data));
        // not store current coupdateCurrentConversationnversation in sessionStorage for archived conversation
        if (!data.is_archived) {
          sessionStorage.setItem("currentConversation", JSON.stringify(data));
        }

        dispatch(
          updateUnreadCountByChatId({ chat_id: data.chat_id, mode: "reset" }),
        );
        dispatch(removeMessageList());
        dispatch(updateSearchMessageResult([]));
        dispatch(updateViewState({ showSearchMessage: false }));
        dispatch(updateSendMessageData({ reply_to: 0 }));
        setSelectedFile(null);

        dispatch(updateViewState({ show_chats_sidebar: false }));
      }
    },
    [dispatch, setSelectedFile, currentConversationData],
  );

  return navigateToChat;
};
