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

import classNames from "classnames";

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

import IcLiveShow from "../../../assets/images/tag/tag-liveshow.svg";
import usePriceInfo from "../../hooks/usePriceInfo";
import { $L } from "../../utils/helperMethods";
import CustomImage from "../CustomImage/CustomImage";
import css from "./TItemCard.module.less";

const SpottableComponent = Spottable("div");

const TYPES = {
  vertical: "vertical",
  horizontal: "horizontal",
  videoShow: "videoShow",
};

const IMAGETYPES = {
  imgHorizontal: "imgHorizontal",
  imgVertical: "imgVertical",
};

// @@pyh Todo, 추후 다국어 resource 추가
const STRING_CONF = {
  SOLD_OUT: $L("SOLD OUT"),
  TOP: $L("TOP"),
};

export const removeDotAndColon = (string) => {
  return /[.:]/.test(string) ? string.replace(/[.:]/g, "") : string;
};

export default memo(function TItemCard({
  children,
  disabled,
  imageAlt,
  imageSource,
  imgType = IMAGETYPES.imgHorizontal,
  logo,
  logoDisplay = false,
  isBestSeller = false,
  isLive = false,
  onBlur,
  onClick,
  onFocus,
  priceInfo,
  productId,
  productName,
  rank,
  soldoutFlag,
  spotlightId,
  nonPosition = false,
  type = TYPES.vertical,
  ...rest
}) {
  const { originalPrice, discountedPrice, discountRate } =
    usePriceInfo(priceInfo) || {};

  const _onBlur = useCallback(() => {
    if (onBlur) {
      onBlur();
    }
  }, [onBlur]);

  const _onClick = useCallback(
    (e) => {
      if (disabled) {
        e.stopPropagation();
        return;
      }

      if (onClick) {
        onClick(e);
      }
    },
    [onClick, disabled]
  );
  const _onFocus = useCallback(() => {
    if (onFocus) {
      onFocus();
    }
  }, [onFocus]);

  return (
    <SpottableComponent
      className={classNames(
        css[type],
        nonPosition && css.nonPosition,
        type === "videoShow" && css[imgType]
      )}
      onBlur={_onBlur}
      onClick={_onClick}
      onFocus={_onFocus}
      spotlightId={
        productId ? "spotlightId-" + removeDotAndColon(productId) : spotlightId
      }
      {...rest}
    >
      <div className={css.imageWrap}>
        <CustomImage alt={imageAlt} delay={0} src={imageSource} />
        {discountRate && <span>{discountRate}</span>}
        {soldoutFlag && soldoutFlag === "Y" && (
          <div>{STRING_CONF.SOLD_OUT}</div>
        )}
      </div>
      <div className={css.descWrap}>
        <h3 className={css.title}>{productName}</h3>
        <p>
          {discountRate ? discountedPrice : originalPrice}
          {discountRate && <span>{originalPrice}</span>}
        </p>
      </div>
      {isBestSeller && rank && (
        <div>
          {STRING_CONF.TOP}
          <span>{rank}</span>
        </div>
      )}
      {isLive && (
        <CustomImage className={css.liveTag} src={IcLiveShow} alt="" />
      )}
    </SpottableComponent>
  );
});

export { IMAGETYPES, TYPES };
