import React, { useEffect, useMemo } from "react";
import PropTypes from "prop-types";
import {
  ReviewList,
  ReviewsBox,
  ReviewsHeader,
  ReviewsTitle,
} from "./UserReviews.styled";

import StarBorderIcon from "@mui/icons-material/StarBorder";
import { useTranslation } from "react-i18next";
import UserReviewsCard from "../Cards/UserReviewsCard/UserReviewsCard";
import NoReviews from "./NoReviews/NoReviews";
import { useDispatch, useSelector } from "react-redux";
import { selectOffer } from "../../store/selectors/offersSelectors";
import { selectSelectedReviews } from "../../store/selectors/reviewSelector";
import { useRouteMatch } from "react-router-dom";
import { fetchReviews } from "../../store/actions/review/reviewActions";

const UserReviews = (props) => {
  const { t } = useTranslation();
  const offer = useSelector(selectOffer);
  const reviews = useSelector(selectSelectedReviews);
  const routeMatch = useRouteMatch();
  const dispatch = useDispatch();

  useEffect(() => {
    console.log(routeMatch);
    if (props.profileReviews && routeMatch.params?.idProfile) {
      let idProfile = routeMatch.params.idProfile;
      dispatch(fetchReviews(idProfile));
    }
  }, [props.profileReviews, routeMatch]);
  const lastThreeReviews = useMemo(() => {
    if (props.givingReview) {
      return [...props.profileReviews];
    }
    if (props.isProfileReviews) {
      return [...reviews.slice(0, 3)];
    }
    if (offer?.companyData?.lastThreeReviews) {
      return [...offer?.companyData.lastThreeReviews];
    }
    return [];
  }, [props.profileReviews, offer, props.isProfileReviews, reviews]);

  return (
    <ReviewsBox
      className={props.className}
      numOfReviews={lastThreeReviews?.length}
    >
      {!props.givingReview && (
        <ReviewsHeader
          container
          direction="row"
          justifyContent="start"
          alignItems="center"
          sx={{ mb: 1.4 }}
        >
          <StarBorderIcon color="action" sx={{ mr: 0.9 }} />
          <ReviewsTitle>{t("reviews.rates")}</ReviewsTitle>
        </ReviewsHeader>
      )}
      <ReviewList>
        {lastThreeReviews?.length > 0 ? (
          lastThreeReviews?.map((review, index) => (
            <UserReviewsCard
              review={review}
              key={index}
              givingReview={props.givingReview}
            />
          ))
        ) : (
          <NoReviews></NoReviews>
        )}
      </ReviewList>
    </ReviewsBox>
  );
};

UserReviews.propTypes = {
  children: PropTypes.node,
  heading: PropTypes.string,
  isProfileReviews: PropTypes.bool,
  profileReviews: PropTypes.any,
  className: PropTypes.string,
  givingReview: PropTypes.bool,
};
UserReviews.defaultProps = {
  isProfileReviews: false,
  profileReviews: [],
};

export default UserReviews;
