import React, { memo, useCallback, useEffect, useMemo, useState } from "react";

import classNames from "classnames";

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

import defaultLogoImg from "../../../../assets/images/ic-tab-partners-default@3x.png";
import CustomImage from "../../../components/CustomImage/CustomImage";
import { convertUtcToLocal } from "../../../components/MediaPlayer/util";
import { $L, removeSpecificTags } from "../../../utils/helperMethods";
import css from "./PlayerItemCard.module.less";

const SpottableComponent = Spottable("div");

const TYPES = {
  liveHorizontal: "liveHorizontal",
  featuredHorizontal: "featuredHorizontal",
};

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

const STRING_CONF = {
  SOLD_OUT: "SOLD OUT",
  TOP: "TOP",
};

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

export default memo(function PlayerItemCard({
  children,
  disabled,
  imageAlt,
  imageSource,
  imgType = IMAGETYPES.imgHorizontal,
  logo,
  onBlur,
  onClick,
  onFocus,
  productId,
  productName,
  soldoutFlag,
  spotlightId,
  patnerName,
  selectedIndex,
  videoVerticalVisible,
  currentVideoVisible,
  dangerouslySetInnerHTML,
  currentTime,
  liveInfo,
  startDt,
  endDt,
  type = TYPES.liveHorizontal,

  ...rest
}) {
  const [focused, setFocused] = useState(false);
  const [percentGauge, setPercentGauge] = useState(0);

  useEffect(() => {
    if (startDt && endDt) {
      let localStartDt = convertUtcToLocal(startDt);
      let localEndDt = convertUtcToLocal(endDt);
      let curDt = new Date();
      let localStartSec = localStartDt?.getTime() / 1000;
      let localEndSec = localEndDt?.getTime() / 1000;
      let curSec = curDt?.getTime() / 1000;
      let fullSec = localEndSec - localStartSec;
      let diff = curSec - localStartSec;

      let percent = Math.floor((diff * 100) / fullSec);

      if (percent > 100) {
        percent = 0;
      }
      setPercentGauge(percent);
    }
  }, [startDt, endDt, currentTime, percentGauge]);

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

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

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

  const progressStyle = useMemo(
    () => ({ width: `${percentGauge}%` }),
    [percentGauge]
  );
  const ariaLabel = "Selected, " + patnerName + " " + productName();

  return (
    <SpottableComponent
      className={classNames(
        css[type],
        !liveInfo && videoVerticalVisible && css.vodVideoVertical,
        liveInfo && videoVerticalVisible && css.liveVideoVertical
      )}
      onBlur={_onBlur}
      onClick={_onClick}
      onFocus={_onFocus}
      spotlightId={
        productId ? "spotlightId-" + removeDotAndColon(productId) : spotlightId
      }
      aria-label={ariaLabel}
      {...rest}
    >
      <div className={css.imageWrap}>
        <CustomImage alt={imageAlt} delay={0} src={imageSource} />
        {soldoutFlag && soldoutFlag === "Y" && (
          <div>{$L(STRING_CONF.SOLD_OUT)}</div>
        )}
        {currentVideoVisible && (
          <div className={css.nowPlay}>
            <h3>{$L("Now Playing")}</h3>
          </div>
        )}
      </div>
      <div className={css.descWrap}>
        <div className={css.patnerWrap}>
          <CustomImage
            className={css.logo}
            src={logo}
            fallbackSrc={defaultLogoImg}
          />
          <h3 className={css.brandName}>{patnerName}</h3>
        </div>

        <h3 dangerouslySetInnerHTML={productName()} className={css.title} />
        {liveInfo && liveInfo.showType === "live" && (
          <div
            className={classNames(
              css.progressBarWrap,
              videoVerticalVisible && css.videoVerticalProgress
            )}
          >
            <div className={css.progressBar}>
              <div
                className={classNames(css.gauge, focused && css.focused)}
                style={progressStyle}
              />
            </div>
          </div>
        )}
      </div>
    </SpottableComponent>
  );
});

export { IMAGETYPES, TYPES };
