import React, { useRef } from "react";
import PropTypes from "prop-types";
import { FilterContainer, FilterIcon, OffersContainer } from "./Offers.styled";
import OfferCard from "../../Cards/OfferCard/OfferCard";
import { useSelector } from "react-redux";
import Paging from "../../Paging/Paging";
import { selectLatestChats } from "../../../store/selectors/chatSelectors";
import { selectUserId } from "../../../store/selectors/loginSelectors";
import { startChat } from "../../../util/helpers/chatHelper";
import OffersNotFound from "./OffersNotFound";
import HeadersMyOffers from "./HeaderMyOffers.js/HeadersMyOffers";
import SkeletonOfferCard from "../../Cards/OfferCard/SkeletonOfferCard/SkeletonOfferCard";

const Offers = (props) => {
  const chats = useSelector(selectLatestChats);
  const offersRef = useRef(null);
  const userId = useSelector(selectUserId);
  const offers = props.offers;
  const arrayForMapping = Array.apply(null, Array(4)).map(() => {});

  const messageOneUser = (offer) => {
    startChat(chats, offer, userId);
  };
  const toggleFilters = () => {
    props.toggleFilters();
  };

  return (
    <>
      <FilterContainer
        onClick={toggleFilters}
        number={offers.filters.numOfFiltersChosen}
        myOffers={props.myOffers}
      >
        <FilterIcon />
      </FilterContainer>
      {!props.skeleton ? (
        <>
          {props.myOffers && (
            <HeadersMyOffers
              searchMyOffers={offers.search.searchOffers}
              handleSearch={offers.apply}
            />
          )}
          {offers.allOffersToShow.length === 0 ? (
            <OffersNotFound />
          ) : (
            <OffersContainer ref={offersRef}>
              {offers.allOffersToShow.map((item) => {
                return (
                  <OfferCard
                    key={item._id}
                    offer={item}
                    halfwidth={props.isGrid}
                    messageUser={messageOneUser}
                  />
                );
              })}
              <Paging
                totalElements={offers.totalOffers}
                elementsPerPage={10}
                current={parseInt(offers.paging.currentPage)}
                changePage={offers.paging.changePage}
              />
            </OffersContainer>
          )}
        </>
      ) : (
        <>
          {arrayForMapping.map((item, index) => (
            <SkeletonOfferCard
              key={index}
              skeleton
              animationStage={props.animationStage}
            />
          ))}
        </>
      )}
    </>
  );
};

Offers.propTypes = {
  children: PropTypes.node,
  isGrid: PropTypes.bool,
  myOffers: PropTypes.bool,
  skeleton: PropTypes.bool,
  animationStage: PropTypes.number,
  offers: PropTypes.any,
  toggleFilters: PropTypes.func,
};

Offers.defaultProps = {
  myOffers: false,
};

export default Offers;
