import React, { useEffect, useMemo, useState } 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 BackdropComponent from "../../MUI/BackdropComponent";
import CreateReview from "../../CreateReview/CreateReview";
import { selectUserId } from "../../../store/selectors/loginSelectors";

const DirectChatHeader = (props) => {
  const exchange = useSelector(selectExchange);
  const userId = useSelector(selectUserId);
  const dispatch = useDispatch();
  const chat = useSelector(selectSelectedChat);
  const [showReviewModal, setShowReviewModal] = useState(false);
  useEffect(() => {
    if (chat?.chat?.exchangeId) {
      refetchExchange();
    }
  }, [chat]);
  const isDisabledReviews = useMemo(() => {
    if (!exchange.valid) return true;
    if (exchange.seller?.userId === userId) {
      if (exchange.seller?.givenReview) return true;
    }
    if (exchange.buyer?.userId === userId) {
      if (exchange.buyer?.givenReview) return true;
    }
    return false;
  }, [exchange, userId]);

  useEffect(() => {
    if (showReviewModal) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "auto";
    }
  }, [showReviewModal]);

  const makeReview = () => {
    setShowReviewModal(true);
  };
  const handleGiveReviewSuccess = () => {
    refetchExchange();
  };
  const refetchExchange = () => {
    dispatch(fetchExchange(chat.chat.exchangeId));
  };
  return (
    <DirectChatHeaderContainer>
      {showReviewModal && (
        <>
          <BackdropComponent
            isLoading
            handleClose={() => setShowReviewModal(false)}
            position="fixed"
          />
          <CreateReview
            offer={props.offer}
            interlocutor={props.interlocutor}
            closeModal={() => setShowReviewModal()}
            handleGiveReviewSuccess={handleGiveReviewSuccess}
            exchange={exchange}
          />
        </>
      )}
      <OfferCard
        offer={props.offer}
        aboveChat
        disabledReviews={isDisabledReviews}
        makeReview={makeReview}
        dontShowViews
      />
    </DirectChatHeaderContainer>
  );
};

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

export default DirectChatHeader;
