import React, { useEffect, useState } from "react";
import { socketInstance } from "../socket/socket";
import { useAppDispatch, useAppSelector } from "../utils/hooks";
import { updateMessageOptions } from "../store/Slices/MessageOptionsSlice";
import { updateViewState } from "../store/Slices/ViewManagerSlice";
import { useNavigate } from "react-router-dom";
import { updateCurrentConversation } from "../store/Slices/CurrentConversationSlice";

export default function LoadInitialData() {
  const dispatch = useAppDispatch();
  const currentConversationData = useAppSelector(
    (state) => state.CurrentConversation,
  );
  const userData = useAppSelector((state) => state.userData);
  const navigate = useNavigate();
  // is_update is for weather chat list is updated or not
  const [is_updated, setis_updated] = useState(true);
  const chatList = useAppSelector((state) => state.chatList);

  useEffect(() => {
    if (chatList?.Chats?.length == 0) {
      dispatch(
        updateViewState({
          is_chatlist_loading: true,
        }),
      );
    }
    socketInstance().emit("chat_list", {
      pageSize: 1000,
      page: 1,
      updatedAt: localStorage.getItem("updatedAt") || "",
    });
  }, []);

  useEffect(() => {
    if (userData.user_id >= 1 && userData.full_name == "") {
      navigate("/user-details");
    } else if (
      userData.user_id >= 1 &&
      (userData.profile_pic == "" ||
        userData.profile_pic.includes("/not-found-images/"))&& window.location.pathname == "/user-details"
    ) {
      navigate("/select-profile");
    }
  }, [userData]);

  useEffect(() => {
    if (
      currentConversationData?.chat_id <= 0 &&
      currentConversationData?.user_id <= 0
    ) {
      return;
    }
    // alert(currentConversationData.chat_id)
    dispatch(
      updateMessageOptions({
        isMessageLoading: true,
      }),
    );
  }, [currentConversationData?.chat_id, currentConversationData?.user_id]);

  useEffect(() => {
    const conversationData = JSON.parse(
      sessionStorage.getItem("currentConversation")!,
    );

    chatList?.Chats?.map((chat) => {
      if (chat.Records[0].chat_id == conversationData?.chat_id && is_updated) {
        setis_updated(false);
        dispatch(
          updateCurrentConversation({
            chat_id: chat.Records[0].chat_id,
            chat_type: chat.Records[0].chat_type,
            full_name: chat.PeerUserData.full_name,
            group_name: chat.Records[0].group_name,
            group_icon: chat.Records[0].group_icon,
            profile_pic: chat.PeerUserData.profile_pic,
            user_id: chat.PeerUserData.user_id,
            is_group_blocked: chat.Records[0]?.blocked_by?.includes(
              userData.user_id.toString(),
            ),
            other_user_blocked_you:
              chat.Records[0]?.blocked_by?.length >= 1 &&
              !chat.Records[0].blocked_by.includes(userData.user_id.toString()),
            user_name: chat.PeerUserData.user_name,
            email_id: chat.PeerUserData.email,
            unseen_count: chat.Records[0].unseen_count,
            updatedAt: chat.PeerUserData.updatedAt!,
            is_message_list_empty: chat.Records[0].Messages.length === 0,
            createdAt: chat.Records[0].createdAt,
            bio: chat.PeerUserData.bio,
            group_description: chat.Records[0].group_description,
            mobile_num: chat.PeerUserData.mobile_num!,
          }),
        );
      }
    });

    // console.log(conversationData, "conversationData");

    // dispatch(updateCurrentConversation(conversationData));
    if (conversationData && Object.keys(conversationData)?.length > 0) {
      dispatch(
        updateViewState({
          show_chats_sidebar: false,
        }),
      );
    }
  }, [dispatch, chatList]);

  return <></>;
}
