import React, { useEffect, useMemo } from "react";
import PropTypes from "prop-types";
import { MiniChatColumnContainer } from "./MiniChatColumn.styled";
import MiniChatCard from "../../Cards/MiniChatCard/MiniChatCard";
import { useDispatch, useSelector } from "react-redux";
import {
  selectLatestChats,
  selectSelectedChat,
} from "../../../store/selectors/chatSelectors";
import { fetchChats } from "../../../store/actions/chat/chatActions";
import MiniChatColumnHeader from "./MiniChatColumnHeader/MiniChatColumnHeaderTitle";
import { useLocation } from "react-router-dom";
import { selectOffer } from "../../../store/selectors/offersSelectors";

const MiniChatColumn = () => {
  const chats = useSelector(selectLatestChats);
  const selectedChat = useSelector(selectSelectedChat);
  const offer = useSelector(selectOffer);
  const location = useLocation();
  const dispatch = useDispatch();
  const newChat = useMemo(() => {
    if (location.state?.offerId) {
      return {
        interlocutorData: {
          image: offer?.companyData?.image,
          name: offer?.companyData?.company?.name,
        },
        offerData: {
          name: offer?.offer?.name,
        },
      };
    }
    return {};
  }, [offer, location.state]);

  useEffect(() => {
    dispatch(fetchChats());
  }, []);
  return (
    <MiniChatColumnContainer>
      <MiniChatColumnHeader />
      {location.state?.offerId && <MiniChatCard chat={newChat} selected />}
      {chats.map((item) => {
        return (
          <MiniChatCard
            key={Date.now() * Math.random()}
            chat={item}
            selected={
              item?.chat?._id === selectedChat?.chat?._id
            }
          />
        );
      })}
    </MiniChatColumnContainer>
  );
};

MiniChatColumn.propTypes = {
  children: PropTypes.node,
};

export default MiniChatColumn;
