import React, { useEffect, useRef } from "react";
import PropTypes from "prop-types";
import {
  DirectChatContentContainer,
  MessageContainer,
  MessagesList,
} from "./DirectChatContent.styled";
import DirectChatContentHeader from "./DirectChatContentHeader/DirectChatContentHeader";
import MessageCard from "../../Cards/MessageCard/MessageCard";
import { useSelector } from "react-redux";
import { selectUserId } from "../../../store/selectors/loginSelectors";
import { selectMineProfilePicture } from "../../../store/selectors/profileSelectors";
import DirectChatNewMessage from "../DirectChatNewMessage/DirectChatNewMessage";

const DirectChatContent = (props) => {
  const messages = props?.chat?.messages;
  const userId = useSelector(selectUserId);
  const myProfileImage = useSelector(selectMineProfilePicture);
  const messagesRef = useRef(null);
  const interlucatorProfileImage = props?.interlucator?.image;
  const handleRefresh = () => {
    props.refreshChat();
  };
  useEffect(() => {
    const offsetBottom =
      messagesRef.current?.offsetTop + messagesRef.current?.offsetHeight;
    messagesRef.current?.scrollTo({ top: offsetBottom, behaviour: "smooth" });
  }, [messages]);
  return (
    <DirectChatContentContainer>
      <DirectChatContentHeader interlucator={props?.interlucator} />
      <MessagesList ref={messagesRef}>
        {messages?.map((item) => {
          const isMyMessage = userId === item.userId;
          const image = isMyMessage ? myProfileImage : interlucatorProfileImage;
          return (
            <MessageContainer key={item?._id}>
              <MessageCard
                message={item}
                image={image}
                isMyMessage={isMyMessage}
              />
            </MessageContainer>
          );
        })}
      </MessagesList>
      <DirectChatNewMessage
        chatId={props?.chat?._id}
        refreshChat={handleRefresh}
      />
    </DirectChatContentContainer>
  );
};

DirectChatContent.propTypes = {
  children: PropTypes.node,
  chat: PropTypes.any,
  interlucator: PropTypes.any,
  refreshChat: PropTypes.func,
};

export default DirectChatContent;
