import React, {
  useState,
  useCallback,
  useRef,
  useEffect,
  useContext,
  useMemo,
} from 'react';
import {
  CardContainer,
  FriendsCardContainer,
  FriendsContainer,
  MessageBody,
  MessagesContainer,
  MessagesWrapper,
  NoChat,
} from "./index.styled";
import InputSection from "../InputSection";
import ReportModal from "./message-modals/report-modal";
import MessageBubble from "./messagebox/messageBubble";
import useMessaging from "../hooks/useMessaging";
import ChatHeader from "./chatheader";
import { getCookie } from "../utils/helpers";
import useRooms from "../hooks/useRooms";
import { NoMessage } from "../assets/svg/noMessage";
import Loader from "../../loader";
import { OutletContext } from "../../AppMainLayout";
import { showErrorToast, showSuccessToast } from "../../customToast";
import DeleteChatModal from "./message-modals/deleteChat-modal";
import MessagesContext, { useMessagesContext } from "../hooks/messagesContext";
import { BsFunnel } from "react-icons/bs";
import { BsChevronDown } from "react-icons/bs";
import { MdOutlineClose } from "react-icons/md";
import DownSvg from "./assets/down";
import CloseSvg from "./assets/close";
import useTranslation from "../../../hooks/useTranslation.jsx";
import wordStore from "../../../mc/wordStore.json";
const Messages = ({
  close,
  user,
  userFullName,
  userType,
  courseName,
  roomID,
  setRoomID,
  userID,
  setUserID,
  userAvatar,
  courseID,
  setCourseID,
  receiverID,
  setReceiverID,
  accountType,
  enterpriseAffiliateID,
  affiliates = false,
}) => {
  const { findText } = useTranslation(wordStore);
  const [showEmoji, setShowEmoji] = useState(false);
  const [chatOptions, setChatOptions] = useState(false);
  const [modalIsOpen, setIsOpen] = useState(false);
  const [editModalIsOpen, setEditModalIsOpen] = useState(false);
  const [previewModalIsOpen, setPreviewModalIsOpen] = useState(false);
  const [deleteChatModalIsOpen, setDeleteChatModalIsOpen] = useState(false);
  const [newMessage, setNewMessage] = useState(null);
  const [allMessages, setAllMessages] = useState([]);
  const [newMessages, setNewMessages] = useState([]);
  const [lastMessage, setLastMessage] = useState(newMessages?.length);
  const [isMessageSending, setIsMessageSending] = useState(false);
  const [mediaForm, setMediaForm] = useState({
    media: null,
  });
  // const {
  //   roomID,
  //   setRoomID,
  //   userID,
  //   setUserID,
  //   userChatList,
  //   setUserChatList,
  // } = useContext(MessagesContext);
  const { generalData, setRightLayout } = useContext(OutletContext);
  const [socketUrl, setSocketUrl] = useState(
    'dev-117782726-api.learngual.com/notify/v1/ws/connect/',
  );
  // const [roomID, setRoomID] = useState("");
  // const [userID, setUserID] = useState("");
  const [userChatList, setUserChatList] = useState([]);
  const [isFullHeight, setIsFullHeight] = useState(true);
  const {
    handleRoomMessage,
    roomMessageData,
    getRoomsData,
    handleCreateMessage,
    createMessageData,
    handleReportUser,
    reportUserData,
    handleClearChat,
    clearChatData,
    createMessageWithMediaData,
    handleCreateMessageWithMedia,
    roomMessageRecipientData,
    handleRoomMessageRecipient,
    roomRecipientDetailsData,
    handleRoomRecipientDetails,
    retrieveMessageData,
    handleRetrieveMessage,
    roomMessageAffiliateData,
    handleRoomMessageAffiliate,
    roomRecipientDetailsPersonalData,
    handleRoomRecipientDetailsPersonal,
    handleRoomRecipientDetailsAffiliate,
  } = useMessaging();
  const {
    handleGetMyRooms,
    getMyRoomsData,
    handleGetPinnedRooms,
    getPinnedRoomsData,
    changePinStatusData,
    handleChangePinStatus,
    getAllRoomsData,
    handleGetAllRooms,
  } = useRooms();
  const chatRecipient = roomRecipientDetailsData?.data;
  const singleChat = getAllRoomsData?.data?.results?.map((user) => {
    return user.id;
  });

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

  useEffect(() => {
    // setRightLayout(false);
  }, []);

  // use effects for successful responses***
  useEffect(() => {
    if (roomMessageData?.response?.status === 200) {
      setAllMessages(roomMessageData?.data?.results?.reverse());
    }
    if (roomMessageAffiliateData?.response?.status === 200) {
      setAllMessages(roomMessageAffiliateData?.data?.results?.reverse());
    }
    if (retrieveMessageData?.response?.status === 200) {
      setAllMessages(retrieveMessageData?.data?.results?.reverse());
    }
    setNewMessages([]);
  }, [
    roomMessageData?.response,
    roomMessageAffiliateData?.response,
    retrieveMessageData?.response,
  ]);

  // useEffect(() => {
  //   if (changePinStatusData?.response?.status === 202) handleGetMyRooms();
  //   handleGetPinnedRooms();
  // }, [changePinStatusData?.response]);

  useEffect(() => {
    if (clearChatData?.response?.status === 204) {
      setDeleteChatModalIsOpen(false);
      location.reload();

      // toast.success("Chat deleted successfully");
    }
  }, [clearChatData?.response]);
  useEffect(() => {
    if (clearChatData?.error)
      showErrorToast(clearChatData?.error?.response?.data?.detail);
  }, [clearChatData?.error]);
  useEffect(() => {
    if (clearChatData?.response?.status)
      showSuccessToast(clearChatData?.data?.detail);
  }, [clearChatData?.response]);
  // use effects for a successful response ends here****

  useEffect(() => {
    setNewMessage([]);
  }, [roomID]);

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

  // useEffect(() => {
  //   setUserID(roomRecipientDetailsData?.data?.id);
  // }, [roomRecipientDetailsData?.data]);

  // retrieve users chats/room messages

  const getMessages = () => {
    if (accountType === 'enterprise') {
      handleRoomMessage(accountType, receiverID, courseID);
      handleRoomRecipientDetails(accountType, receiverID, courseID);
    }
    if (!affiliates && accountType === 'instructor') {
      handleRoomMessage(accountType, receiverID, courseID);
      handleRoomRecipientDetails(accountType, receiverID, courseID);
    }
    if (affiliates && accountType === "instructor") {
      handleRoomMessageAffiliate(
        receiverID,
        courseID,
        roomID,
        enterpriseAffiliateID
      );
      handleRoomRecipientDetailsAffiliate(
        enterpriseAffiliateID,
        receiverID,
        courseID
      ); //check later
      // handleRoomRecipientDetails(accountType, receiverID, courseID);
    }
    if (accountType === 'personal') {
      handleRetrieveMessage(receiverID, courseID, roomID);
      handleRoomRecipientDetailsPersonal(receiverID, courseID);
    }
  };
  useEffect(() => {
    if (receiverID && courseID) {
      getMessages();
    }
  }, [receiverID, courseID, roomID]);
  useEffect(() => {
    if (createMessageData?.data || createMessageWithMediaData?.data) {
      if (accountType === 'enterprise') {
        handleRoomMessage(accountType, receiverID, courseID);
        handleRoomRecipientDetails(accountType, receiverID, courseID);
      }
      if (!affiliates && accountType === 'instructor') {
        handleRoomMessage(accountType, receiverID, courseID);
        handleRoomRecipientDetails(accountType, receiverID, courseID);
      }
      if (affiliates && accountType === "instructor") {
        handleRoomMessageAffiliate(
          receiverID,
          courseID,
          roomID,
          enterpriseAffiliateID
        );
        handleRoomRecipientDetailsAffiliate(
          enterpriseAffiliateID,
          receiverID,
          courseID
        ); //
      }
      if (accountType === 'personal') {
        handleRetrieveMessage(receiverID, courseID, roomID);
        handleRoomRecipientDetailsPersonal(receiverID, courseID);
      }
    }
  }, [createMessageData?.data, createMessageWithMediaData?.data]);

  //console.log("allMessages", allMessages);
  //console.log("handleRoomMessage", roomMessageData);

  // All web sockets initialization********************
  const token = getCookie('access');
  const account_id = generalData?.accounts?.results?.map((item) => item?.id)[0];
  const socket = useRef();

  //console.log("account_id", account_id);
  // const websocket = new WebSocket(
  //   `wss://${socketUrl}?account=${account_id}&authorization=${token}`
  // );

  useEffect(() => {
    const websocket = new WebSocket(
      `wss://${socketUrl}?account=${account_id}&authorization=${token}`,
    );
    socket.current = websocket;
    websocket.onopen = () => {
      //check if socket is connected
      console.log('websocket connection established');
    };
    websocket.onmessage = (event) => {
      const data = JSON.parse(event.data);
      if (data.event === 'new.message.result') {
        if (data.data) {
          // setNewMessages((prev) => [...prev, data.data]);
          // setNewMessage(data.data);
          getMessages(accountType, receiverID, courseID, roomID);
          // if (data.data.sender.id === receiverID) {
          // }
          if (!data.data?.user_message) {
          }
        }
      }
      console.log('websocket data', data);
    };
    return () => {
      socket.current.close();
      console.log("websocket closed");
    };
  }, []);

  // All web sockets initialization Ends Here

  useEffect(() => {
    const chatListCopy = userChatList.map((chat) => {
      if (chat.id === newMessage.id) {
        return {
          ...chat,
          last_message: newMessage,
        };
      }
      return chat;
    });
    const sortedList = chatListCopy?.sort(
      (chatA, chatB) =>
        new Date(chatA.last_message.created_at).getTime() -
        new Date(chatB.last_message.created_at).getTime(),
    );
    setUserChatList(sortedList);
    if (newMessage?.room?.id === roomID) {
      // setAllMessages((prev) => [...prev, newMessage]);
    } else {
      //console.log(userChatList);
    }
    return () => {};
  }, [newMessage]);

  // Handle user scroll to update previous messages
  const scrollRef = useRef();
  const handleScroll = () => {
    const { scrollTop, scrollHeight, clientHeight } = scrollRef.current;
    if (scrollTop + clientHeight === scrollHeight) {
      //console.log("Reached the bottom!");
      // Execute your desired action here, like showing an alert
    } else {
    }
  };
  useEffect(() => {
    const divElement = scrollRef?.current;
    divElement?.addEventListener("scroll", handleScroll);
    return () => {
      divElement?.removeEventListener('scroll', handleScroll);
    };
  }, [scrollRef]);
  const messagesEndRef = useRef(null);
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({
      behavior: "smooth",
    });
  }, [allMessages]); // Run this effect whenever `allMessages` changes

  return (
    <>
      <MessagesWrapper>
        <div className="message_by_wrapper">
          <p className="mbw_name">
            {findText("Message")}
            {userFullName}{" "}
          </p>

          <div className="icon-box">
            <span onClick={() => setIsFullHeight(!isFullHeight)}>
              <DownSvg />
            </span>
            <span onClick={close}>
              <CloseSvg />
            </span>
          </div>
        </div>
        <MessagesContainer isFullHeight={isFullHeight}>
          <CardContainer>
            <>
              <ChatHeader
                chatOptions={chatOptions}
                setChatOptions={setChatOptions}
                openModal={() => {
                  setIsOpen(true);
                }}
                chatRecipient={chatRecipient}
                roomID={roomID}
                handleChangePinStatus={handleChangePinStatus}
                handleClearChat={handleClearChat}
                deleteChatModal={() => {
                  setDeleteChatModalIsOpen(true);
                }}
                userFullName={userFullName}
                userType={userType}
                courseName={courseName}
                userAvatar={userAvatar}
                accountType={accountType}
              />

              <MessageBody ref={scrollRef}>
                {roomMessageData?.loading && <></>}
                {allMessages?.length > 0 ? (
                  <>
                    {allMessages?.map((chat, idx) => (
                      <>
                        <div className="date__section">
                          <span>{chat?.date}</span>
                        </div>
                        {chat?.messages
                          ?.map((chat, idx) => (
                            <MessageBubble
                              chat={chat}
                              idx={idx}
                              createMessageData={createMessageData}
                            />
                          ))
                          .reverse()}

                        {newMessages?.map((chat, idx) => (
                          <MessageBubble
                            chat={chat}
                            idx={idx}
                            createMessageData={createMessageData}
                            isMessageSending={isMessageSending}
                            // setNewMessages={setNewMessages}
                            newMessages={newMessages}
                            lastMessage={lastMessage}
                          />
                        ))}
                        {/* Add a dummy div to scroll to */}
                        <div ref={messagesEndRef} />
                      </>
                    ))}
                  </>
                ) : (
                  <>
                    {!roomMessageData?.loading && (
                      <NoChat>
                        <NoMessage />
                        <h5>{findText("No Chat History")}</h5>
                        <p>
                          {findText(
                            "No message in your inbox yet! Type, send an image"
                          )}{" "}
                          <br />
                          {findText("or audio recording to start chatting.")}
                        </p>
                      </NoChat>
                    )}
                  </>
                )}
              </MessageBody>
              <div className="input">
                <InputSection
                  setShowEmoji={setShowEmoji}
                  userID={userID}
                  setPreviewModalIsOpen={setPreviewModalIsOpen}
                  mediaForm={mediaForm}
                  setMediaForm={setMediaForm}
                  setAllMessages={setAllMessages}
                  allMessages={allMessages}
                  newMessages={newMessages}
                  setNewMessages={setNewMessages}
                  setIsMessageSending={setIsMessageSending}
                  lastMessage={lastMessage}
                  setLastMessage={setLastMessage}
                  handleRoomMessage={handleRoomMessage}
                  roomID={roomID}
                  accountType={accountType}
                  courseID={courseID}
                  affiliates={affiliates}
                  handleCreateMessage={handleCreateMessage}
                  createMessageData={createMessageData}
                  enterpriseAffiliateID={enterpriseAffiliateID}
                  receiverID={receiverID}
                />
              </div>
            </>
          </CardContainer>

          {/********** Modals *********/}
          <ReportModal
            isOpen={modalIsOpen}
            userID={userID}
            modalIsOpen={modalIsOpen}
            setIsOpen={setIsOpen}
          />

          <DeleteChatModal
            isOpen={deleteChatModalIsOpen}
            userID={userID}
            deleteChatModalIsOpen={deleteChatModalIsOpen}
            setDeleteChatModalIsOpen={setDeleteChatModalIsOpen}
            handleClearChat={() => handleClearChat(roomID)}
          />
        </MessagesContainer>
      </MessagesWrapper>
    </>
  );
};
export default Messages;
