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

import classNames from "classnames";

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

import ImgLiveShow from "../../../../../../assets/images/tag/tag-liveshow.png";
import CustomImage from "../../../../../components/CustomImage/CustomImage";
import { convertUtcToLocal } from "../../../../../components/MediaPlayer/util";
import { convertToTimeFormat } from "../../../../../utils/helperMethods";
import css from "./LiveVideoCard.module.less";

const SpottableComponent = Spottable("div");

export default memo(function LiveVideoCard({
  isFocused,
  itemInfo,
  onBlur,
  onClick,
  onFocus,
  onLoad,
  liveYn,
  ...rest
}) {
  const [imageLoaded, setIsImageLoaded] = useState(false);

  const { endDt, showNm, strtDt, thumbnailImgPath, vtctpYn } = itemInfo;

  const ariaLabel = "LIVE SHOW " + showNm;
  const isVertical = Boolean(vtctpYn === "Y");

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

  const _onClick = useCallback(() => {
    if (onClick) {
      onClick();
    }
  }, [onClick]);

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

  const _onLoad = useCallback(() => {
    setIsImageLoaded(true);

    if (onLoad) {
      onLoad();
    }
  }, [onLoad]);

  return (
    <SpottableComponent
      className={classNames(css.card, isFocused && css.shadow)}
      onBlur={_onBlur}
      onClick={_onClick}
      onFocus={_onFocus}
      aria-label={ariaLabel}
      {...rest}
    >
      <figure
        className={classNames(
          css.videoThumbnail,
          isVertical ? css.vertical : css.horizontal
        )}
      >
        <CustomImage
          src={thumbnailImgPath}
          alt={showNm}
          ariaLabel={showNm}
          onLoad={_onLoad}
        />
      </figure>
      {liveYn === "Y" && (
        <div className={css.videoInfo}>
          <CustomImage src={ImgLiveShow} alt="Live Icon" />
          <h3>{showNm.replace(/<br\s*\/?>/gi, " ")}</h3>
          <time>
            {convertToTimeFormat(convertUtcToLocal(strtDt))} ~{" "}
            {convertToTimeFormat(convertUtcToLocal(endDt))}
          </time>
        </div>
      )}

      {imageLoaded && <div className={css.darkGradient} />}
    </SpottableComponent>
  );
});
