import InfiniteScroll from "react-infinite-scroll-component";
import MyMessage from "./MyMessage";
import { formatUTCtoLocalDate } from "../../../utils/formatUTCtoLocalDate";
import { useAppDispatch, useAppSelector } from "../../../utils/hooks";
import { useEffect, useState } from "react";
import OnClickScrollToBottom from "./OnClickScrollToBottom";
import LoadMoreMessages from "./LoadMoreMessages";
import { updateMessageOptions } from "../../../store/Slices/MessageOptionsSlice";
import scrollToMessage from "../../../utils/scrollToMessage";
import { ClipLoader } from "react-spinners";
import { useTheme } from "../../../context/ThemeProvider";
import SystemMessage from "./SystemMessage";

export default function MessageBody() {
  const MessageListArray = useAppSelector((state) => state.MessageList);
  const NavigateTospesificMessage = useAppSelector(
    (state) => state.NavigateToSpesificMessage,
  );
  const messageListDetails = useAppSelector((state) => state.MessageOptions);
  const dispatch = useAppDispatch();
  const [isIOS, setIsIOS] = useState(false);
  // @ts-ignore
  const { theme } = useTheme();
  useEffect(() => {
    setIsIOS(/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream);
  }, []);

  const urls = MessageListArray.message_list?.Records?.filter(
    (message) =>
      ["image", "video", "gif"].includes(message.message_type!) &&
      message.message_content,
  );

  const image_urls = urls?.map((message) =>
    message.message_content.replace(/\\/g, "/"),
  );

  const fetchMoreMessages = () => {
    dispatch(updateMessageOptions({ messageListAtTop: true }));
  };

  useEffect(() => {
    if (
      MessageListArray.message_list?.Records?.length !== 0 &&
      NavigateTospesificMessage.navigate_to_message === false
    ) {
      if (
        messageListDetails.currentPage === "1" ||
        messageListDetails.currentPage === ""
      ) {
        const lastMsg =
          MessageListArray.message_list.Records[
            MessageListArray.message_list.Records.length - 1
          ];
        if (lastMsg) {
          scrollToMessage(lastMsg.message_id, false, false);
        }
      }
    }
  }, []);

  return (
    <div
      id="messageListDiv"
      className={`flex ${location.pathname !== "/video-call" ? "h-[83dvh]" : "h-[78dvh] lg:h-[76dvh]"} lg:w-full flex-col-reverse gap-y-2 overflow-y-auto ${location.pathname !== "/video-call" ? "sm:px-14 lg:px-20" : "px-2 lg:px-0 "} ${isIOS ? "pb-20" : "pb-16"} lg:py-6`}
    >
      <OnClickScrollToBottom />
      <LoadMoreMessages />
      <InfiniteScroll
        dataLength={MessageListArray.message_list?.Records?.length || 0}
        next={fetchMoreMessages}
        hasMore={
          messageListDetails.totalPages > Number(messageListDetails.currentPage)
        }
        inverse={true}
        loader={
          <ClipLoader size={23} color={theme == "dark" ? "white" : "black"} />
        }
        scrollableTarget="messageListDiv"
      >
        {MessageListArray.message_list?.Records?.map((e) => {
          if (e.message_type === "date") {
            return (
              <div
                key={e.message_id}
                id={String(e.message_id)}
                className="mx-auto my-3 w-fit rounded-full bg-messageHead px-5 py-1 text-center text-sm font-medium text-darkText shadow-sm"
              >
                {new Date(e.createdAt).toDateString() ===
                new Date().toDateString()
                  ? "Today"
                  : new Date(e.createdAt).toDateString() ===
                      new Date(Date.now() - 24 * 60 * 60 * 1000).toDateString()
                    ? "Yesterday"
                    : formatUTCtoLocalDate(e.createdAt)}
              </div>
            );
          } else if (
            [
              "group-created",
              "member-added",
              "member-removed",
              "promoted-as-admin",
              "removed-as-admin",
              "member-left",
              "block",
            ].includes(e.message_type)
          ) {
            return <SystemMessage messageData={e} />;
          } else {
            return (
              <MyMessage
                key={e.message_id}
                messageData={e}
                image_urls={image_urls}
              />
            );
          }
        })}
      </InfiniteScroll>
    </div>
  );
}
