import React, { useCallback } from 'react';

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

import css from './SubCategoryItem.module.less';

const SpottableComponent = Spottable("div");

export default function SubCategoryItem({
  subCategoryData,
  itemNum,
  currentLgCatCd,
  ...rest
}) {
  const parsePriceInfo = useCallback(
    (priceInfo) => {
      const priceParts = itemNum.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 };
    },
    [itemNum.priceInfo]
  );

  const { originalPrice, discountedPrice, discountRate } = parsePriceInfo(
    itemNum.priceInfo
  );
  return (
    <SpottableComponent {...rest} className={css.vertical}>
      <div>
        <img src={itemNum.imgUrl} alt={itemNum.prdtNm} />

        {discountRate && <span>{discountRate}</span>}
      </div>
      <div>
        <h3>{itemNum.prdtNm}</h3>
        <p>
          {discountRate ? discountedPrice : originalPrice}
          {discountRate && <span>{originalPrice}</span>}
        </p>
      </div>
    </SpottableComponent>
  );
}
