import React, { useEffect, useMemo } from "react";
import PropTypes from "prop-types";
import { DirectChatHeaderContainer } from "./DirectChatHeader.styled";
import OfferCard from "../../Cards/OfferCard/OfferCard";
import { useSelector } from "react-redux";
import { selectExchange } from "../../../store/selectors/exchangeSelector";
import { useDispatch } from "react-redux";
import { fetchExchange } from "../../../store/actions/exchange/exchangeActions";
import { selectSelectedChat } from "../../../store/selectors/chatSelectors";
import { selectUserId } from "../../../store/selectors/loginSelectors";
import { toggleCreateReviewModal } from "../../../store/actions/modal/modalActions";

const DirectChatHeader = (props) => {
  const exchange = useSelector(selectExchange);
  const userId = useSelector(selectUserId);
  const dispatch = useDispatch();
  const chat = useSelector(selectSelectedChat);

  useEffect(() => {
    if (chat?.chat?.exchangeId) refetchExchange();
  }, [chat]);

  const isDisabledReviews = useMemo(() => {
    if (!exchange.valid) return true;
    if (exchange.seller?.userId === userId && exchange.seller?.givenReview)
      return true;
    if (exchange.buyer?.userId === userId && exchange.buyer?.givenReview)
      return true;
    return false;
  }, [exchange, userId]);

  const showReviewModal = () => {
    dispatch(
      toggleCreateReviewModal({
        offer: props.offer,
        interlocutor: props.interlocutor,
        exchange: exchange,
      })
    );
  };

  const refetchExchange = () => {
    dispatch(fetchExchange(chat.chat.exchangeId));
  };

  const acceptExchange = () => {
    props.acceptExchange();
  };
  return (
    <DirectChatHeaderContainer>
      <OfferCard
        offer={props.offer}
        aboveChat
        disabledReviews={props.interlocutor?._blocked || isDisabledReviews}
        makeReview={showReviewModal}
        acceptExchange={acceptExchange}
        exchangeState={props?.exchangeState}
        dontShowViews
        disabledCheckButton={
          props.interlocutor?._blocked || props?.offer?._deleted
        }
      />
    </DirectChatHeaderContainer>
  );
};

DirectChatHeader.propTypes = {
  children: PropTypes.node,
  offer: PropTypes.any,
  interlocutor: PropTypes.any,
  acceptExchange: PropTypes.func,
  exchangeState: PropTypes.any,
};

export default DirectChatHeader;
