import React, { useEffect, useState } from "react";
import { PostsImgSuit } from "./MyPosts.styled";

// const dummyData2 = [
//   {
//     alt: "Remy Sharp",
//     src: "/static/images/avatar/1.jpg",
//     title: "Gitara",
//     text: (<React.Fragment><PostsImgSuit/> Player.rs</React.Fragment>)
//   },
//   {
//     alt: "Remy Sharp",
//     src: "/static/images/avatar/1.jpg",
//     title: "Gitara",
//     text: (<React.Fragment><PostsImgSuit/> Player.rs</React.Fragment>)
//   }
// ]
import HeaderPopover from "../HeaderPopover/HeaderPopover";
import { useTranslation } from "react-i18next";
import { useDispatch, useSelector } from "react-redux";
import { selectMineOffers } from "../../../store/selectors/offersSelectors";
import { fetchMineOffers } from "../../../store/actions/offers/offersActions";
import { selectProfileName } from "../../../store/selectors/profileSelectors";
import { useHistory } from "react-router-dom";
import { MY_OFFERS_PAGE } from "../../../constants/pages";

export const MyPosts = () => {
  const { t } = useTranslation();
  const dispatch = useDispatch();
  const mineOffers = useSelector(selectMineOffers);
  const name = useSelector(selectProfileName);
  const history = useHistory();
  const [arrayOfMineOffers, setArrayOfMineOffers] = useState([]);
  useEffect(() => {
    dispatch(fetchMineOffers());
  }, []);
  useEffect(() => {
    if (mineOffers?.length > 0) {
      if (mineOffers.length > 1) {
        setArrayOfMineOffers(
          [mineOffers[0], mineOffers[1]].map((item) => ({
            src: item.images[0],
            title: item.name,
            onClick: () => goToOffer(item._id),
            text: (
              <React.Fragment>
                <PostsImgSuit /> {name}
              </React.Fragment>
            ),
          }))
        );
      } else if (mineOffers.length > 0) {
        setArrayOfMineOffers(
          [mineOffers[0]].map((item) => ({
            alt: "Photo",
            src: item.images[0],
            title: item.name,
            onClick: () => goToOffer(item._id),
            text: (
              <React.Fragment>
                <PostsImgSuit /> {name}
              </React.Fragment>
            ),
          }))
        );
      } else {
        setArrayOfMineOffers([]);
      }
    }
  }, [mineOffers]);

  const goToOffer = (id) => {
    history.push(`/proizvodi/${id}`);
  };
  const goToMySwaps = () => {
    history.push(MY_OFFERS_PAGE);
  };
  return (
    <HeaderPopover
      title={t("header.myOffers")}
      items={arrayOfMineOffers}
      buttonText={t("header.checkEverything")}
      buttonOnClick={goToMySwaps}
    />
  );
};
