/* eslint-disable @typescript-eslint/ban-ts-comment */
/* eslint-disable @typescript-eslint/no-non-null-asserted-optional-chain */
import MessageHeader from "./MessageHeader";
import MessageBody from "./MessageBody";

import { useAppSelector } from "../../../utils/hooks";
import ConversationInfoDrawer from "../GroupInfo/ConversationInfoDrawer";
import SendMessage from "./SendMessage/SendMessage";
import IfUserBlocked from "./SendMessage/IfUserBlocked";

import { useTheme } from "../../../context/ThemeProvider";
import { ClipLoader } from "react-spinners";
import EmptyMessageList from "./EmptyMessageList";
import SearchMessageDrawer from "../GroupInfo/SearchMessageDrawer";
import DeleteSelectedMessage from "./SelectedMessageOption/DeleteSelectedMessage";
import ForwardSelectedMessage from "./SelectedMessageOption/ForwardSelectedMessage";
import { useConversationInfo } from "../../../store/api/useConversationInfo";
import IfGropIsBlockedByAdmin from "./SendMessage/IfGropIsBlockedByAdmin";
import { useMessageList } from "../../../socket/useMessageList";
import { useEffect } from "react";
import { updateMessageList } from "../../../store/Slices/MessageListSlice";
import { updateMessageOptions } from "../../../store/Slices/MessageOptionsSlice";
import { useAppDispatch } from "../../../utils/hooks";

import { MessageListRes } from "../../../types/MessageListType";
import { UseQueryResult } from "react-query";
import scrollToMessage from "../../../utils/scrollToMessage";
import { socketInstance } from "../../../socket/socket";
import { removeUnSeenMessages } from "../../../store/Slices/UnSeenMessagesSlice";

export default function MessageList() {
  const MessageListArray = useAppSelector((state) => state.MessageList);
  const MessageOptions = useAppSelector((state) => state.MessageOptions);
  const currentConversationData = useAppSelector(
    (state) => state.CurrentConversation,
  );
  const { data: conversationInfo } = useConversationInfo();
  const unSeenMessages = useAppSelector((state) => state.UnSeenMessages);
  const dispatch = useAppDispatch();
  // @ts-ignore
  const { theme } = useTheme();

  const { data: messageListData }: UseQueryResult<MessageListRes, Error> =
    useMessageList(
      currentConversationData.chat_id,
      currentConversationData.user_id!,
      Number(MessageOptions.currentPage),
    )!;

  useEffect(() => {
    // alert(currentConversationData.is_message_list_empty)
    if (messageListData?.message_list?.Records?.length! > 0) {
      dispatch(updateMessageList(messageListData!));
      setTimeout(() => {
        scrollToMessage(
          messageListData?.message_list?.Records?.[0]?.message_id!,
          false,
          false,
        );
      }, 10);
      dispatch(
        updateMessageOptions({
          // currentPage: String(
          //   messageListData?.message_list?.Pagination?.current_page,
          // ),
          totalPages: Number(
            messageListData!.message_list?.Pagination?.total_pages,
          ),
          isMessageLoading: false,
          isMoreMessageLoading: false,
          messageListAtTop: false,
        }),
      );
    } else {
      if (currentConversationData.chat_id <= 0) {
        dispatch(
          updateMessageOptions({
            isMessageLoading: false,
          }),
        );
      } else if (currentConversationData.is_message_list_empty) {
        dispatch(
          updateMessageOptions({
            isMessageLoading: false,
          }),
        );
      }
    }
  }, [
    messageListData,
    currentConversationData.chat_id,
    currentConversationData.is_conversation_changed,
  ]);

  //This is for, blue tick is not working if user has allready opend some chat and navigate to other chat and then some message receive ,and after user return to chat then it does not consider as read
  useEffect(() => {
    unSeenMessages
      .filter((e) => e.chat_id == currentConversationData.chat_id)
      .map((e) => {
        socketInstance().emit("real_time_message_seen", {
          chat_id: e.chat_id,
          message_id: e.message_id,
          status: "seen",
        });
        dispatch(removeUnSeenMessages(e));
      });
  }, [currentConversationData.chat_id]);

  return (
    <>
      <MessageHeader />
      {MessageOptions.isMessageLoading ? (
        <div className="flex h-[83dvh] flex-col items-center justify-center gap-y-2 overflow-y-auto px-14 pb-10 lg:py-6">
          <ClipLoader color={theme == "dark" ? "white" : "black"} />
        </div>
      ) : (
        <>
          {MessageListArray.message_list?.Records?.length === 0 ? (
            <EmptyMessageList />
          ) : (
            <MessageBody />
          )}
        </>
      )}

      <ConversationInfoDrawer />
      <SearchMessageDrawer />

      {MessageOptions.selectMessage ? (
        MessageOptions.delete_message ? (
          <DeleteSelectedMessage />
        ) : MessageOptions.forward_message ? (
          <ForwardSelectedMessage />
        ) : (
          <SendMessage />
        )
      ) : currentConversationData.is_group_blocked ? (
        <IfUserBlocked />
      ) : currentConversationData.other_user_blocked_you ? (
        <IfUserBlocked />
      ) : conversationInfo?.conversationDetails.blocked_by_admin ? (
        <IfGropIsBlockedByAdmin />
      ) : (
        <SendMessage />
      )}
    </>
  );
}
