import React, {
  memo,
  useCallback,
} from 'react';

import classNames from 'classnames';

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

import { $L } from '../../utils/helperMethods';
import { SpotlightIds } from '../../utils/SpotlightIds';
import css from './TItemCard.module.less';

const SpottableComponent = Spottable("li");

const TYPE_VERTICAL = "vertical";
const TYPE_HORIZONTAL = "horizontal";

const SOLD_OUT_STRING = "SOLD OUT";
const TOP_STRING = "TOP";

export default memo(function TItemCard({
  children,
  imageAlt,
  imageSource,
  isBestSeller = false,
  onCardClick,
  priceInfo,
  productId,
  productName,
  rank,
  soldoutFlag,
  type = TYPE_VERTICAL,
  ...rest
}) {
  const handleClick = useCallback(
    (productId) => {
      onCardClick && onCardClick(productId);
    },
    [onCardClick, productId]
  );

  const parsePriceInfo = useCallback(
    (priceInfo) => {
      const priceParts = 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 };
    },
    [priceInfo]
  );

  const { originalPrice, discountedPrice, discountRate } =
    parsePriceInfo(priceInfo);

  return (
    <SpottableComponent
      {...rest}
      className={classNames(
        type === TYPE_HORIZONTAL && css.horizontal,
        type === TYPE_VERTICAL && css.vertical
      )}
      onClick={() => handleClick(productId)}
      spotlightId={SpotlightIds.TITEM_CARD + productId}
    >
      <div>
        <img src={imageSource} alt={imageAlt} />
        {discountRate && <span>{discountRate}</span>}
        {soldoutFlag && soldoutFlag === "Y" && <div>{$L(SOLD_OUT_STRING)}</div>}
      </div>
      <div>
        <h3>{productName}</h3>
        <p>
          {discountRate ? discountedPrice : originalPrice}
          {discountRate && <span>{originalPrice}</span>}
        </p>
      </div>
      {isBestSeller && rank && (
        <div>
          {$L(TOP_STRING)}
          <span>{rank}</span>
        </div>
      )}
    </SpottableComponent>
  );
});
