import React, { useState, useEffect, useMemo, useRef } from "react";
import PropTypes from "prop-types";
import {
  ReviewList,
  ReviewsBox,
  ReviewsHeader,
  ReviewsHeaderTitle,
  ReviewsTitle,
  UserReviewsContainer,
} 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,
  setReviews,
  fetchReviewsAsAdmin,
} from "../../store/actions/review/reviewActions";
import { selectIsLoadingByActionType } from "../../store/selectors/loadingSelectors";
import SkeletonUserReviews from "./SkeletonUserReviews/SkeletonUserReviews";
import { ONE_OFFER_SCOPE } from "../../store/actions/offers/offersActionConstants";
import {
  REVIEW_GET_SCOPE,
  REVIEW_GET_AS_ADMIN_SCOPE,
} from "../../store/actions/review/reviewActionConstants";
import ReviewsSorting from "./ReviewsSorting/ReviewsSorting";
import { sortReviews } from "../../util/helpers/reviewsHelper";
// import { selectUserId } from "../../store/selectors/loginSelectors";

const UserReviews = (props) => {
  const [isGiven, setIsGiven] = useState(true);
  const { t } = useTranslation();
  const offer = useSelector(selectOffer);
  const reviews = useSelector(selectSelectedReviews);
  const routeMatch = useRouteMatch();
  const dispatch = useDispatch();
  const listRef = useRef(null);
  const sortRef = useRef(null);
  // const userId = useSelector(selectUserId);

  const isLoadingReview = useSelector(
    selectIsLoadingByActionType(
      props.isAdmin
        ? REVIEW_GET_AS_ADMIN_SCOPE
        : props.isProfileReviews
        ? REVIEW_GET_SCOPE
        : ONE_OFFER_SCOPE
    )
  );


  useEffect(() => {
    let idProfile = routeMatch.params?.profileId;
    if (idProfile) {
      if (props.isAdmin) {
        dispatch(fetchReviewsAsAdmin(idProfile));
      } else {
        dispatch(fetchReviews(idProfile));
      }
    }

    // if (props.profileReviews && routeMatch.params?.profileId) {
    //   let idProfile = routeMatch.params?.profileId;
    //   dispatch(fetchReviews(idProfile));
    // }
  }, [props.profileReviews, routeMatch]);
  const lastThreeReviews = useMemo(() => {
    if (props.isAdmin) {
      if (isGiven) {
        return reviews.givenReviews;
      } else {
        return reviews.receivedReviews;
      }
    }
    if (props.isProfileReviews) {
      return reviews;
    }
    if (props.givingReview) {
      return [...props.profileReviews];
    }
    if (offer?.companyData?.lastThreeReviews) {
      // Making array of reviews in same order(sorting) so when comparing
      // them, I can make valid condition
      if (
        JSON.stringify(sortReviews(reviews)) !==
        JSON.stringify(sortReviews(offer?.companyData?.lastThreeReviews))
      ) {
        dispatch(setReviews([...offer?.companyData.lastThreeReviews]));
      }
      return [...offer?.companyData?.lastThreeReviews];
    }
    return [];
  }, [props.profileReviews, offer, props.isProfileReviews, reviews, isGiven]);

  const handleChangeSorting = (newSortOption) => {
    listRef.current.scrollTo({ top: 0, behaviour: "smooth" });
    if (props.isAdmin) {
      if (newSortOption.value === 1) {
        setIsGiven(true);
      } else {
        setIsGiven(false);
      }
    }
  };

  return (
    <UserReviewsContainer className={props.className}>
      {!props.givingReview &&
      (isLoadingReview || isLoadingReview === undefined) ? (
        <SkeletonUserReviews />
      ) : (
        <ReviewsBox
          isAdmin={props.isAdmin}
          profile={props.isProfileReviews}
          numOfReviews={lastThreeReviews?.length}
        >
          {!props.givingReview && (
            <ReviewsHeader
              container
              direction="row"
              justifyContent="start"
              alignItems="center"
              sx={{ mb: 1.4 }}
            >
              <ReviewsHeaderTitle>
                <StarBorderIcon
                  color="action"
                  sx={{ mr: 0.9, position: "relative", top: 6 }}
                />
                <ReviewsTitle>{t("reviews.rates")}</ReviewsTitle>
              </ReviewsHeaderTitle>
              <ReviewsSorting
                changeSorting={handleChangeSorting}
                ref={sortRef}
                isAdmin={props.isAdmin}
              />
            </ReviewsHeader>
          )}
          <ReviewList ref={listRef} isProfileReviews={props.isProfileReviews}>
            {lastThreeReviews?.length > 0 ? (
              lastThreeReviews?.map((review, index) => (
                <UserReviewsCard
                  showRemoveIcon={props.isAdmin}
                  review={review}
                  key={index}
                  isAdmin={props.isAdmin}
                  hasGivenReview={isGiven}
                  givingReview={props.givingReview}
                  rightReviews={props.rightReviews}
                />
              ))
            ) : (
              <NoReviews></NoReviews>
            )}
          </ReviewList>
        </ReviewsBox>
      )}
    </UserReviewsContainer>
  );
};

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

export default UserReviews;
