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

import classNames from 'classnames';

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

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

const SpottableComponent = Spottable("div");

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 { originalPrice, discountedPrice, discountRate } =
    usePriceInfo(priceInfo);

  const handleClick = useCallback(
    (productId) => {
      onCardClick && onCardClick(productId);
    },
    [onCardClick, productId]
  );

  return (
    <SpottableComponent
      {...rest}
      className={classNames(
        type === TYPE_HORIZONTAL && css.horizontal,
        type === TYPE_VERTICAL && css.vertical,
        isBestSeller === true && css.homeBestSeller
      )}
      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>
  );
});
