import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Box, Typography } from "@mui/material";
import MessagesSection from "./messagesSection";
import ProfileSection from "./profileSection";
import TypingArea from "./TypingArea";
import {
  createEchoInstance,
  fetchChatHistory,
  getPrivateChannel,
  getUserIdLocalStorage,
} from "@/components/common/common";
import { renderEmptyState } from "../common/commonFunctions";
import {
  replaceChat,
  setActiveUser,
  setAdditionalSuggestions,
  setRatingStatus,
  setRoomId,
  setRoomParticipants,
  setUsersList,
} from "@/hooks/ChatReducer";
import { AttachedMessage } from "@/hooks/Interface";
import {
  BoldHeadings,
  EmptyBigChatRoomRight,
  EmptySellerImage,
  OuterChatContainer,
  SubText,
} from "@/components/ChatModule/style";
import { AllMsgList, EmptyChatSection } from "../style";
import ChatActionPrompt from "../common/components/chatActionPrompt";
import AdditionalSuggestionContent from "../common/components/additionSuggestionBox.tsx/AdditionalSuggestionContent";

/**
 * ChatRoom component
 * @param {Object} props - Props object containing handleUsersListShow and handleOpenSuggestions functions
 * @returns {JSX.Element} - Rendered component
 */

function ChatRoom(props) {
  const { handleMobileToggleSection } = props;

  const [attachedMessageDetails, setAttachedMessageDetails] =
    useState<AttachedMessage | null>(null);
  const dispatch = useDispatch();
  const {
    chats,
    activeUser,
    usersList,
    userTabs,
    roomParticipants,
    ratingStatus,
    chatRequest,
  } = useSelector((state: any) => state.chatData) || {};
  const {
    user_info: { id: userID },
  } = useSelector((state: any) => state?.userData);

  const {
    detail: { data = {} },
  } = useSelector((state: any) => state.productDetail);
  const { request_status, request_send_from, user_type } = activeUser;

  const {
    user_id = "",
    id: product_id,
    product_name,
    unique_number,
    price_term,
    unit_price,
  } = data || {};

  const currentLoggedUserId = getUserIdLocalStorage();

  const {
    showAllUsers = false,
    showArchiveUsers = false,
    showBlockedUsers = false,
    showUnreadUsers = false,
    showNewRequestUsers = false,
    showCalls = false,
    showGroups = false,
    showChats = false,
  } = userTabs || {};

  const unread_users = usersList?.filter(
    (user) => user?.unread_count > 0 && user?.is_archived === 0
  );

  useEffect(() => {
    const privateChannel = getPrivateChannel(currentLoggedUserId, "userStatus");

    const handleStatusChange = (e) => {
      const { status, user_id } = e;
      if (+activeUser?.id === +user_id) {
        const updatedActiveUser = { ...activeUser, online: status };
        dispatch(setActiveUser(updatedActiveUser));
      }
      if (usersList.length > 0) {
        const updatedUsersList = usersList.map((user) => {
          if (user?.id === user_id) {
            return { ...user, online: status };
          }
          return user;
        });
        dispatch(setUsersList(updatedUsersList));
      }
    };

    privateChannel?.listen("UserOnlineStatus", handleStatusChange);

    return () =>
      privateChannel?.stopListening("UserOnlineStatus", handleStatusChange);
  }, [activeUser?.room_id, usersList]);

  useEffect(() => {
    if (!(window as any).Echo) {
      createEchoInstance();
    }

    //if the active userId available or user is logged In And quotationUrl is not available in active user, Then only fetch the chat history.
    if (
      (activeUser?.id || user_id) &&
      !activeUser?.quotationUrl &&
      localStorage?.userData &&
      JSON.parse(localStorage?.userData).id !== user_id
    ) {
      const paramsToFetch =
        activeUser?.is_group === 1
          ? `room_id=${activeUser?.room_id}`
          : "search=&type=all";
      fetchChatHistory({
        userId: user_id || activeUser?.id,
        params: paramsToFetch,
        url: "",
      })
        .then((responseData) => {
          const { message = "", room_id } = responseData?.data || {};
          //In user_status - Getting the all user details available in the specific Room.
          const { user_status } = responseData;
          // dispatch(setRoomParticipants(user_status));
          const activeUsersID = user_id || activeUser?.id;
          const userIndex = user_status.findIndex(
            (user) => user?.user_id === activeUsersID
          );
          if (userIndex !== -1) {
            const { online, company, user_id, name, avatar_original } =
              user_status[userIndex];
            const { rating_status, all } = message;
            const { data, nextPageUrl } = all;
            dispatch(replaceChat(data));
            dispatch(setRoomId(room_id));
            dispatch(setRatingStatus(rating_status));
            const initialActiveUser = {
              room_id: room_id,
              name: name,
              id: user_id,
              online: online,
              companyName: company,
              avatar_original: avatar_original,
              previousChatUrl: nextPageUrl,
              product_id,
              product_name: product_name,
              unique_number,
              price_term,
              unit_price,
              is_pinned: 0,
            };
            const isUserIsAlreadyExist = usersList.find(
              (user) => +user.id === user_id
            );
            dispatch(setActiveUser(initialActiveUser));
            if (!isUserIsAlreadyExist && usersList.length > 0) {
              const clonnedUsersList = [...usersList];
              clonnedUsersList.push(initialActiveUser);
              dispatch(setUsersList(clonnedUsersList));
            }
          }
        })
        .catch((error) => {
          console.error(error);
        });
    }
  }, []);

  const setAttatchMessageState = () => {
    setAttachedMessageDetails(null);
  };

  const handleReplyMessage = (id: number, message: string) => {
    setAttachedMessageDetails({ id: id, message: message });
  };

  // const showRatingSection = roomParticipants.find(participant => {
  //   const { id, rating_status, rating_added_date } = participant || {};

  //   // Check if participant matches the active user and has rating_status
  //   if (id === activeUser?.id && rating_status) {
  //     // Check if rating_added_date exists and is within the last 24 hours
  //     return (
  //       rating_added_date &&
  //       (currentDate - new Date(rating_added_date).getTime()) < 86400000 // 24 hours in milliseconds
  //     );
  //   }
  //   return false;
  // });

  const handleAdditionalSuggestionsPopup = () => {
    dispatch(setAdditionalSuggestions({ isOpen: false }));
  };
  const isSeller = user_type === "seller";

  const renderChatSection = () => {
    if (chats?.length !== 0 || activeUser?.id) {
      return (
        <>
          {/** Top Message Rendering Section */}
          <MessagesSection
            handleReplyMessage={handleReplyMessage}
            attachedMessageDetails={attachedMessageDetails}
            setAttatchMessageState={setAttatchMessageState}
          />

          {request_status === "pending" &&
            +currentLoggedUserId !== +request_send_from && (
              <ChatActionPrompt
                content='Choose "Accept" to engage and respond to the message, "Reject" to decline the chat completely.'
                type="firstTimeChatInitiate"
              />
            )}

          {!ratingStatus && chats.length > 8 && (
            <ChatActionPrompt
              content={`Would you like to give a review for the ${
                isSeller ? "Supplier" : "Buyer"
              }?`}
              type="rateSupplier"
            />
          )}

          {/** Top Typing Section */}
          <TypingArea
            attachedMessageDetails={attachedMessageDetails}
            setAttatchMessageState={setAttatchMessageState}
          />
        </>
      );
    }

    if (props?.isAdmin === "admin" && chats?.length === 0) {
      if (showCalls) {
        return renderEmptyState(
          "/assets/chat/no-call-data.svg",
          "No Calls Yet",
          "Looks like you haven't initiated a Telephonic with any of our sellers"
        );
      }
      if (showGroups) {
        return renderEmptyState(
          "/assets/chat/no-chat-group.svg",
          "No Groups Yet",
          "Looks like you haven't initiated a telephonic conversation with any of our sellers"
        );
      }
      if (showAllUsers || showArchiveUsers || showBlockedUsers) {
        return (
          <EmptyBigChatRoomRight>
            <OuterChatContainer>
              <Box>
                <BoldHeadings>Add Seller To Start Chat</BoldHeadings>
              </Box>
              <Box>
                <SubText>
                  Start a chat by adding seller by showing interest in the
                  particular <br /> product to find new opporunities
                </SubText>
              </Box>
              <EmptySellerImage>
                <img
                  src="/assets/chat/seller-emptyimage.svg"
                  alt=""
                  width="300px"
                />
              </EmptySellerImage>
              <Box>
                <BoldHeadings>No Messages Yet</BoldHeadings>
              </Box>
              <Box>
                <SubText>
                  Looks like you haven't initiated a conversation with <br />
                  any of our sellers
                </SubText>
              </Box>
            </OuterChatContainer>
          </EmptyBigChatRoomRight>
        );
      }
      if (showUnreadUsers) {
        if (unread_users?.length === 0) {
          return renderEmptyState(
            "/assets/chat/no-unread-msg.svg",
            "No Unread Messages",
            "Looks like you haven't initiated a conversation with <br /> any of our sellers"
          );
        } else {
          return (
            <EmptyBigChatRoomRight>
              <OuterChatContainer>
                <Box>
                  <BoldHeadings>Add Seller To Start Chat</BoldHeadings>
                </Box>
                <Box>
                  <SubText>
                    Start a chat by adding seller by showing interest in the
                    particular <br /> product to find new opporunities
                  </SubText>
                </Box>
                <EmptySellerImage>
                  <img
                    src="/assets/chat/seller-emptyimage.svg"
                    alt=""
                    width="300px"
                  />
                </EmptySellerImage>
                <Box>
                  <BoldHeadings>No Unread Messages</BoldHeadings>
                </Box>
                <Box>
                  <SubText>
                    Looks like you haven't initiated a conversation with <br />
                    any of our sellers
                  </SubText>
                </Box>
              </OuterChatContainer>
            </EmptyBigChatRoomRight>
          );
        }
      }
    } else {
      return (
        <AllMsgList className={chats?.length === 0 && "chat-emptypage"}>
          <EmptyChatSection>
            <img src="/assets/chat/no_live_chat_img.svg" alt="chat empty" />
            <Typography>
              Chat and source on the go with
              <Typography style={{ color: "#d7282f" }}>Powercozmo</Typography>
            </Typography>
          </EmptyChatSection>
        </AllMsgList>
      );
    }
  };

  return (
    <>
      <AdditionalSuggestionContent
        handleAdditionalSuggestionsPopup={handleAdditionalSuggestionsPopup}
      />
      {/** Top Profile Section */}
      {activeUser && (
        <ProfileSection
          handleDraw={props?.handleDraw}
          isAdmin={props?.isAdmin}
          handleMobileToggleSection={handleMobileToggleSection}
        />
      )}
      {renderChatSection()}
    </>
  );
}
export default ChatRoom;
