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

import classNames from "classnames";
import { useDispatch } from "react-redux";

import { Job } from "@enact/core/util";
import Spotlight from "@enact/spotlight";
import Spottable from "@enact/spotlight/Spottable";
import { Marquee } from "@enact/ui/Marquee";

import ic_crown from "../../../../../assets/images/icons/ic-crown-badge@3x.png";
import ic_warning from "../../../../../assets/images/icons/ic-warning@3x.png";
// import ic_call from "../../../../../assets/images/icons/ic-wh-call@3x.png";
import {
  finishVideoPreview,
  startVideoPlayer,
} from "../../../../actions/playActions";
import CustomImage from "../../../../components/CustomImage/CustomImage";
import css from "./PopularVideoCard.module.less";
import { sendLogTotalRecommend } from "../../../../actions/logActions";
import { LOG_CONTEXT_NAME, LOG_MESSAGE_ID } from "../../../../utils/Config";
import { SpotlightIds } from "../../../../utils/SpotlightIds";

const SpottableComponent = Spottable("div");

// const PHONE_STRING = "Phone";
const WARNING_STRING = "warning";

const TYPE = {
  horizontal: "horizontal",
  vertical: "vertical",
};

const PopularVideoCard = ({
  disclaimer,
  expsOrd,
  handleItemClick,
  handleItemFocus,
  isOnTop,
  lgCatCd,
  onSpotlightDown,
  patncNm,
  patnrId,
  showId,
  showNm,
  spotlightId,
  thumbnailType = TYPE.horizontal,
  thumbnailImgPath,
  selectedIndex,
  brndNm,
  currentShelf,
}) => {
  const dispatch = useDispatch();

  const [isFocused, setIsFocused] = useState(false);

  const isFullScreenModeActiveRef = useRef(false);
  const videoFocusTimeoutJob = useRef(new Job((func) => func(), 1000));

  useEffect(() => {
    if (isFullScreenModeActiveRef.current && isOnTop) {
      setTimeout(() => {
        if (Spotlight.getPointerMode()) {
          dispatch(finishVideoPreview());
          isFullScreenModeActiveRef.current = false;
        }
      });
    }
  }, [isOnTop]);

  useEffect(() => {
    const videoFocusTimeoutJobValue = videoFocusTimeoutJob.current;

    if (isFocused) {
      videoFocusTimeoutJobValue.start(() => {
        dispatch(
          startVideoPlayer({
            showId,
            patnrId,
            shptmBanrTpNm: "VOD",
            thumbnail: thumbnailImgPath,
            lgCatCd: lgCatCd,
            patncNm,
            modal: true,
            modalContainerId: spotlightId, //to calc width, height, left, top
            modalClassName: css.videoModal,
          })
        );

        isFullScreenModeActiveRef.current = true;
      });
    } else {
      videoFocusTimeoutJobValue.stop();
      dispatch(finishVideoPreview());
    }
  }, [isFocused, dispatch, showId]);

  const onFocus = useCallback(() => {
    setIsFocused(true);

    if (handleItemFocus) handleItemFocus();
  }, [handleItemFocus]);

  const onBlur = useCallback(() => {
    setIsFocused(false);
  }, []);

  const onClick = useCallback(() => {
    setIsFocused(false);

    dispatch(
      startVideoPlayer({
        showId,
        patnrId,
        shptmBanrTpNm: "VOD",
        thumbnail: thumbnailImgPath,
        lgCatCd: lgCatCd,
        patncNm,
        modal: false,
        modalContainerId: spotlightId, //to calc width, height, left, top
        modalClassName: css.videoModal,
      })
    );

    const params = {
      contextName: LOG_CONTEXT_NAME.TRENDING_NOW,
      messageId: LOG_MESSAGE_ID.SHELF_CLICK,
      shelfLocation: 1,
      shelfId: SpotlightIds.TRENDING_NOW_POPULAR_SHOW,
      shelfTitle: currentShelf,
      showId: showId,
      showTitle: showNm,
      partner: patncNm,
      location: selectedIndex + 1,
    };
    dispatch(sendLogTotalRecommend(params));

    if (handleItemClick) handleItemClick();
  }, [dispatch, showId, spotlightId, handleItemClick]);

  const _onSpotlightDown = useCallback(
    (ev) => {
      if (onSpotlightDown) onSpotlightDown(ev);
    },
    [onSpotlightDown]
  );

  return (
    <SpottableComponent
      className={classNames(css.card, isFocused && css.focused)}
      onBlur={onBlur}
      onClick={onClick}
      onFocus={onFocus}
      spotlightId={spotlightId}
      onSpotlightDown={_onSpotlightDown}
      aria-label={"SHOW " + showNm}
    >
      <figure className={css[thumbnailType]}>
        {thumbnailImgPath && (
          <CustomImage
            delay={0}
            src={thumbnailImgPath}
            animationSpeed="fast"
            alt={showNm}
          />
        )}
      </figure>
      <div className={classNames(css.videoDesc, isFocused && css.descFocused)}>
        <div>
          <h3>{showNm && showNm}</h3>
          <div className={css.rank}>
            <img src={ic_crown} alt="" />
            <div>{expsOrd}</div>
          </div>
        </div>
        <div className={css.notice}>
          <Marquee className={css.marquee} marqueeOn="render">
            <img src={ic_warning} alt={WARNING_STRING} />
            <span>{disclaimer}</span>
          </Marquee>
        </div>
      </div>
    </SpottableComponent>
  );
};

export default memo(PopularVideoCard);
