import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { useDispatch, useSelector } from "react-redux";
import { useHistory } from "react-router-dom";
import { fetchHeaderChats } from "../../../store/actions/chat/chatActions";
import { selectLatestChats } from "../../../store/selectors/chatSelectors";
import { selectUserId } from "../../../store/selectors/loginSelectors";
import HeaderPopover from "../HeaderPopover/HeaderPopover";
import PropTypes from "prop-types";
import { makeErrorToastMessage } from "../../../store/utils/makeToastMessage";
import { EyeIcon } from "./MyMessages.styled";

export const MyMessages = (props) => {
  const { t } = useTranslation();
  const dispatch = useDispatch();
  const userId = useSelector(selectUserId);
  const chats = useSelector(selectLatestChats);
  const history = useHistory();
  const [lastChats, setLastChats] = useState([]);

  const convertMessages = (messages) => {
    return messages
      .map((item) => ({
        src: item.interlocutorData.image,
        title: item.interlocutorData.name,
        onClick: () => goToMessage(item?.chat?._id),
        text: "Proizvod: ",
        bigText: item.offerData.name,
      }))
      .slice(0, 2);
  };

  useEffect(() => {
    if (userId?.length > 1 && chats?.length === 0) {
      dispatch(fetchHeaderChats(userId));
    }
  }, [userId]);
  useEffect(() => {
    if (chats?.length > 0) {
      setLastChats([...convertMessages(chats)]);
    }
  }, [chats]);
  const goToMessages = () => {
    if (lastChats.length !== 0) {
      history.push(`/messages/${chats[0].chat?._id}`);
      props.closePopover();
    } else {
      makeErrorToastMessage(t("messages.noMessagesToast"));
      props.closePopover();
    }
  };
  const goToMessage = (chatId) => {
    history.push(`/messages/${chatId}`);
    props.closePopover();
  };
  return (
    <HeaderPopover
      title={t("header.myMessages")}
      items={lastChats}
      buttonOnClick={goToMessages}
      buttonText={t("header.checkEverything")}
      buttonIcon={<EyeIcon color={chats?.length === 0} />}
      noMessages={chats?.length === 0}
    />
  );
};

MyMessages.propTypes = {
  closePopover: PropTypes.func,
};
