import React, { useCallback } from "react";

import Spottable from "@enact/spotlight/Spottable";

import css from "./HomeOnSaleItem.module.less";

const SpottableComponent = Spottable("div");

export default function HomeOnSaleItem({ homeOnSaleInfos, itemData, ...rest }) {
  const parsePriceInfo = useCallback(
    (priceInfo) => {
      const priceParts = itemData.priceInfo
        .split("|")
        .filter((part) => part !== "N")
        .map((item) => item.trim());

      let originalPrice, discountedPrice, discountRate;
      if (priceParts.length === 4) {
        [originalPrice, discountedPrice, , discountRate] = priceParts;
      } else if (priceParts.length === 2) {
        [originalPrice, discountedPrice] = priceParts;
        discountRate = null;
      } else {
        originalPrice = null;
        discountedPrice = null;
        discountRate = null;
      }

      return { originalPrice, discountedPrice, discountRate };
    },
    [itemData.priceInfo]
  );
  const { originalPrice, discountedPrice, discountRate } = parsePriceInfo(
    itemData.priceInfo
  );

  return (
    <SpottableComponent className={css.onSaleItemList} {...rest}>
      <img src={itemData.imgUrl} className={css.onSaleItemListImg} />
      <div className={css.onSaleItemListBox}>
        <div className={css.onSaleItemListBoxTitle}>{itemData.catNm}</div>
        {discountRate && (
          <div className={css.onSaleItemListBoxSaleBox}>
            up to&nbsp;
            <span className={css.onSaleItemListBoxSaleBoxPer}>
              {discountRate}
            </span>
          </div>
        )}
        <div className={css.onSaleItemListBoxName}>{itemData.prdtNm}</div>
        <div className={css.onSaleItemListBoxPrice}>
          {discountedPrice}
          {discountRate && (
            <span className={css.onSaleItemListBoxPriceStripe}>
              {originalPrice}
            </span>
          )}
        </div>
      </div>
    </SpottableComponent>
  );
}
