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

import { useDispatch, useSelector } from "react-redux";

import { Job } from "@enact/core/util";
import Spotlight from "@enact/spotlight";
import SpotlightContainerDecorator from "@enact/spotlight/SpotlightContainerDecorator";
import {
  getContainerId,
  setContainerLastFocusedElement,
} from "@enact/spotlight/src/container";

import ImgNoProductDefault from "../../../../../assets/images/img-no-data@3x.png";
import ImgNoProductJuvelirochka from "../../../../../assets/images/img-brands-juvelirochka@3x.png";
// import ImgNoProductShopLC from "../../../../../assets/images/img-brands-shop-lc@3x.png";
import { updatePanel } from "../../../../actions/panelActions";
import {
  finishVideoPreview,
  startVideoPlayer,
} from "../../../../actions/playActions";
import { panel_names } from "../../../../utils/Config";
import { $L } from "../../../../utils/helperMethods";
import css from "./LiveChannelsVerticalContents.module.less";
import LiveChannelsVerticalProductList from "./LiveChannelsVerticalProductList/LiveChannelsVerticalProductList";
import LiveVideoCard from "./LiveVideoCard/LiveVideoCard";
import { sendLogTotalRecommend } from "../../../../actions/logActions";

const Container = SpotlightContainerDecorator(
  { enterTo: "last-focused" },
  "div"
);

const STRING_CONF = {
  NO_PRODUCT_MESSAGE: "Loading Product Details. Please Wait...",
};

const LiveChannelsVerticalContents = ({
  brandChanInfoItem,
  contentsIndex,
  handleItemFocus,
  isOnTop,
  selectedPatnrId,
  spotlightId,
  shelfTitle,
  shelfOrder,
}) => {
  const dispatch = useDispatch();

  const cntry_cd = useSelector((state) => state.common.httpHeader?.cntry_cd);
  const cursorVisible = useSelector(
    (state) => state.common.appStatus.cursorVisible
  );

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

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

  const {
    brandProductInfo,
    chanId,
    patnrId,
    showId,
    showUrl,
    showNm,
    lgCatNm,
    chanNm,
    brndNm,
    liveYn,
  } = brandChanInfoItem;

  const isJuvelirochka = useMemo(
    () => cntry_cd === "RU" && patnrId === "12",

    [cntry_cd, patnrId]
  );

  useEffect(() => {
    if (brandProductInfo && brandProductInfo.length > 0) {
      const containerId = "live-channels-vertical-contents-id-" + contentsIndex;
      const container = document.getElementById(containerId);

      if (container) {
        const gridListId = getContainerId(
          container.children[1].children[0].children[0]
        );
        const gridList = container.children[1].children[0].children[0];
        if (gridListId && gridList) {
          setContainerLastFocusedElement(null, [gridListId]);
        }
      }
    }
  }, [brandProductInfo, contentsIndex, selectedPatnrId]);

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

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

    if (isFocused) {
      videoFocusTimeoutJobValue.start(() => {
        dispatch(
          startVideoPlayer({
            chanId,
            modal: true,
            modalContainerId: "spotlightId-featuredBrands-liveChannels",
            modalClassName: css.player,
            patnrId,
            showId,
            showUrl,
            shptmBanrTpNm: liveYn === "Y" ? "LIVE" : "VOD",
          })
        );
      });
    } else {
      videoFocusTimeoutJobValue.stop();
      dispatch(finishVideoPreview());
    }
  }, [chanId, dispatch, isFocused, patnrId, showId, showUrl]);

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

  const handleClick = useCallback(() => {
    const lastFocusedTarget = Spotlight.getCurrent();
    const lastFocusedTargetId =
      lastFocusedTarget?.getAttribute("data-spotlight-id");

    if (lastFocusedTargetId) {
      const section = "live-channels-vertical";
      const x = 0;

      dispatch(
        updatePanel({
          name: panel_names.FEATURED_BRANDS_PANEL,
          panelInfo: {
            lastFocusedTargetId,
            patnrId,
            section,
            x,
          },
        })
      );

      dispatch(
        startVideoPlayer({
          chanId,
          modal: false,
          modalContainerId: "spotlightId-featuredBrands-liveChannels",
          modalClassName: css.player,
          patnrId,
          showId,
          showUrl,
          shptmBanrTpNm: liveYn === "Y" ? "LIVE" : "VOD",
          sourcePanel: panel_names.FEATURED_BRANDS_PANEL,
        })
      );

      dispatch(
        sendLogTotalRecommend({
          partner: chanNm,
          shelfLocation: shelfOrder,
          shelfId: spotlightId,
          shelfTitle: shelfTitle,
          contentId: showId,
          contentTitle: showNm,
          brand: brndNm,
          location: contentsIndex + 1,
          category: lgCatNm,
        })
      );

      isFullScreenModeActivedRef.current = true;
    }

    videoFocusTimeoutJob.current.stop();
  }, [chanId, dispatch, patnrId, showId, showUrl, liveYn]);

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

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

  const getNoProductImg = useCallback((countryCode, partnerId) => {
    let img = ImgNoProductDefault;

    if (countryCode === "RU" && partnerId === "12") {
      img = ImgNoProductJuvelirochka;
    }

    return img;
  }, []);

  return (
    <Container
      className={css.container}
      id={"live-channels-vertical-contents-id-" + contentsIndex}
    >
      <LiveVideoCard
        data-video-card={"live-channels-vertical-video-card"}
        isFocused={isFocused}
        itemInfo={brandChanInfoItem}
        onBlur={handleBlur}
        onClick={handleClick}
        onFocus={handleFocus}
        liveYn={liveYn}
        spotlightId={"spotlightId-featuredBrands-liveChannels"}
      />
      {brandProductInfo && brandProductInfo.length > 0 ? (
        <LiveChannelsVerticalProductList
          brandProductInfo={brandProductInfo}
          chanId={chanId}
          handleItemFocus={handleItemFocus}
          patnrId={patnrId}
          selectedPatnrId={selectedPatnrId}
          showId={showId}
          showNm={showNm}
          showUrl={showUrl}
          spotlightId={spotlightId}
          shelfOrder={shelfOrder}
          shelfTitle={shelfTitle}
          catNm={lgCatNm}
          patnerName={chanNm}
          liveYn={liveYn}
        />
      ) : (
        <figure>
          <div>
            <img
              className={
                !isJuvelirochka
                  ? css.noProductDefault
                  : css.noProductJuvelirochka
              }
              src={getNoProductImg(cntry_cd, patnrId)}
              alt=""
            />
            {!isJuvelirochka && (
              <figcaption>{$L(STRING_CONF.NO_PRODUCT_MESSAGE)}</figcaption>
            )}
          </div>
        </figure>
      )}
    </Container>
  );
};

export default memo(LiveChannelsVerticalContents);
