import React, { useEffect, useMemo } from "react";
import PropTypes from "prop-types";
import { DirectChatContainer } from "./DirectChat.styled";
import DirectChatHeaderTitle from "./DirectChatHeaderTitle/DirectChatHeaderTitle";
import DirectChatHeader from "./DirectChatHeader/DirectChatHeader";
import { useDispatch, useSelector } from "react-redux";
import { useLocation, useRouteMatch } from "react-router-dom";
import { fetchOneChat, setOneChat } from "../../store/actions/chat/chatActions";
import {
  selectSelectedChat,
} from "../../store/selectors/chatSelectors";
import DirectChatContent from "./DirectChatContent/DirectChatContent";
import { selectOffer } from "../../store/selectors/offersSelectors";
import { fetchOneOffer } from "../../store/actions/offers/offersActions";

const DirectChat = () => {
  const chat = useSelector(selectSelectedChat);
  const offer = useSelector(selectOffer);
  const routeMatch = useRouteMatch();
  const location = useLocation();
  const dispatch = useDispatch();

  const offerObject = useMemo(() => {
    if (location?.state?.offerId) {
      return offer?.offer;
    }
    return chat?.offer?.offer;
  }, [chat, location.state, offer]);

  const chatObject = useMemo(() => {
    if (location?.state?.offerId) {
      return {};
    }
    return chat?.chat;
  }, [chat, location.state]);

  const interlocutorObject = useMemo(() => {
    if (location?.state?.offerId) {
      return {
        image: offer?.companyData?.image,
        name: offer?.companyData?.company?.name,
        location: offer?.companyData?.company?.contacts?.location,
      };
    }
    return chat?.interlocutor;
  }, [chat, location.state, offer]);

  useEffect(() => {
    if (routeMatch.params.idChat) {
      refreshChat();
    }
  }, [routeMatch.params.idChat, location.state?.offerId]);

  const refreshChat = () => {
    if (routeMatch.params.idChat === "newMessage") {
      dispatch(fetchOneOffer(location.state.offerId));
      dispatch(setOneChat({}));
    } else {
      dispatch(fetchOneChat(routeMatch.params.idChat));
    }
  };
  return (
    <DirectChatContainer>
      <DirectChatHeaderTitle />
      <DirectChatHeader offer={offerObject} interlocutor={interlocutorObject} />
      <DirectChatContent
        chat={chatObject}
        interlucator={interlocutorObject}
        refreshChat={refreshChat}
      />
    </DirectChatContainer>
  );
};

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

export default DirectChat;
