import React, { useEffect } from "react";

import { useDispatch, useSelector } from "react-redux";

import { SpotlightContainerDecorator } from "@enact/spotlight/SpotlightContainerDecorator";
import Spottable from "@enact/spotlight/Spottable";

import { getOnSaleInfo } from "../../../actions/onSaleActions";
import { $L } from "../../../utils/helperMethods";
import css from "./OnSale.module.less";

const Container = SpotlightContainerDecorator(
  { leaveFor: { left: "", right: "" }, enterTo: "last-focused" },
  "div"
);

const SpottableComponent = Spottable("li");

const OnSale = ({
  isOnTop,
  spotlightId,
  onScrollTop,
  onScrollShelf,
  ...rest
}) => {
  const dispatch = useDispatch();
  const HomeSaleInfos = useSelector(
    (state) => state.onSale.onSaleData.homeOnSaleInfos
  );

  useEffect(() => {
    dispatch(getOnSaleInfo({ categoryIncFlag: "Y", lgCatCd: "" }));
  }, []);

  return (
    <Container {...rest} spotlightId={spotlightId} className={css.container}>
      <div className={css.bestSeller}>
        <h2 className={css.subTitle}>{$L("ON SALE")}</h2>
        <ul className={css.onSaleItem}>
          {HomeSaleInfos &&
            HomeSaleInfos.map((item, index) => {
              const priceInfo = item.priceInfo;
              let salePrice;
              const originalPrice = priceInfo.split("|")[0];
              if (priceInfo.split("|")[3] == "") {
                salePrice = priceInfo.split("|")[1];
              } else {
                salePrice = priceInfo.split("|")[1];
              }
              item.priceInfo.split("|")[0];
              return (
                <SpottableComponent key={index} className={css.onSaleItemList}>
                  <img src={item.imgUrl} className={css.onSaleItemListImg} />
                  <div className={css.onSaleItemListBox}>
                    <div className={css.onSaleItemListBoxTitle}>
                      {item.catNm}
                    </div>
                    <div className={css.onSaleItemListBoxSaleBox}>
                      up to&nbsp;
                      <span className={css.onSaleItemListBoxSaleBoxPer}>
                        {item.dcRate}%
                      </span>
                    </div>
                    <div className={css.onSaleItemListBoxName}>
                      {item.prdtNm}
                    </div>
                    <div className={css.onSaleItemListBoxPrice}>
                      {salePrice}
                      <span className={css.onSaleItemListBoxPriceStripe}>
                        {originalPrice}
                      </span>
                    </div>
                  </div>
                </SpottableComponent>
              );
            })}
        </ul>
      </div>
    </Container>
  );
};

export default OnSale;
