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

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

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

import { updatePanel } from "../../../../../actions/panelActions";
import { startVideoPlayer } from "../../../../../actions/playActions";
import TItemCard, {
  removeDotAndColon,
} from "../../../../../components/TItemCard/TItemCard";
import TVirtualGridList from "../../../../../components/TVirtualGridList/TVirtualGridList";
import useScrollTo from "../../../../../hooks/useScrollTo";
import {
  LOG_CONTEXT_NAME,
  LOG_MESSAGE_ID,
  panel_names,
} from "../../../../../utils/Config";
import {
  getTranslate3dValueByDirection,
  scaleH,
} from "../../../../../utils/helperMethods";
import css from "./RecommendedShowsProductList.module.less";

export default function RecommendedShowsProductList({
  brandRecommendedShowProductInfo,
  videoThumbnail,
  catCd,
  contentsIndex,
  handleItemFocus,
  patnrId,
  selectedCatCd,
  selectedPatnrId,
  showId,
  shelfOrder,
  shelfTitle,
  spotlightId,
  patnerName,
  contentTitle,
  contentId,
  catNm,
}) {
  const { getScrollTo, scrollLeft } = useScrollTo();

  const dispatch = useDispatch();

  const panelInfo = useSelector((state) => state.panels.panels[0]?.panelInfo);

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

  const scrollLeftJob = useRef(new Job((func) => func(), 0));

  useEffect(() => {
    const scrollLeftJobValue = scrollLeftJob.current;

    if (panelInfo?.section !== "recommended-shows") {
      return;
    }

    if (panelInfo?.exprOrd === contentsIndex + 1) {
      const { x } = panelInfo;

      if (x === 0) {
        return;
      }

      scrollLeftJobValue.start(() => scrollLeft({ x }));
    }

    return () => {
      if (panelInfo?.exprOrd === contentsIndex + 1) {
        scrollLeftJobValue.stop();
      }
    };
  }, [contentsIndex, panelInfo, scrollLeft]);

  useEffect(() => {
    scrollLeft();
  }, [scrollLeft, selectedCatCd, selectedPatnrId]);

  const handleClick = useCallback(
    (prdtId, index) => (e) => {
      const tItemCard = e.currentTarget;

      const lastFocusedTarget = Spotlight.getCurrent();
      const lastFocusedTargetId =
        lastFocusedTarget?.getAttribute("data-spotlight-id");
      const exprOrd = parseInt(
        lastFocusedTarget?.getAttribute("data-exposure-order")
      );

      const xContainer = tItemCard?.parentNode?.parentNode;

      if (exprOrd && lastFocusedTargetId && xContainer) {
        const section = "recommended-shows";
        const x = getTranslate3dValueByDirection(xContainer);

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

      let y =
        index < 2
          ? 0
          : index === 2
          ? scaleH(208)
          : scaleH(index * 248 - 248 - 40);

      dispatch(
        startVideoPlayer({
          modal: false,
          patnrId,
          prdtId,
          showId,
          shptmBanrTpNm: "VOD",
          thumbnail: videoThumbnail,
          targetId: "spotlightId-" + prdtId,
          y,
        })
      );
    },
    [catCd, dispatch, patnrId, showId, videoThumbnail]
  );

  const handleFocus = useCallback(() => {
    if (handleItemFocus) {
      handleItemFocus();
    }

    if (cursorVisible) {
      return;
    }
  }, [cursorVisible, handleItemFocus]);

  const renderItem = useCallback(
    ({ index, ...rest }) => {
      const {
        imgUrl, //
        offerInfo,
        prdtId,
        prdtNm,
        priceInfo,
        soldoutFlag,
        brndNm,
      } = brandRecommendedShowProductInfo[index];

      return (
        <TItemCard
          contextName={LOG_CONTEXT_NAME.FEATURED_BRANDS}
          messageId={LOG_MESSAGE_ID.SHELF_CLICK}
          shelfLocation={shelfOrder}
          shelfTitle={shelfTitle}
          shelfId={spotlightId}
          patnerName={patnerName}
          catNm={catNm}
          order={index + 1}
          contentTitle={contentTitle}
          contentId={contentId}
          brandName={brndNm}
          data-exposure-order={contentsIndex + 1}
          data-product-card={"recommended-shows-product-card-" + contentsIndex}
          imageAlt={prdtNm}
          imageSource={imgUrl}
          onClick={handleClick(prdtId, index)}
          onFocus={handleFocus}
          offerInfo={offerInfo}
          priceInfo={priceInfo}
          productId={prdtId}
          productName={prdtNm}
          soldoutFlag={soldoutFlag}
          spotlightId={
            "recommended-shows-spotlightId-" + removeDotAndColon(prdtId)
          }
          label={
            contentsIndex * 1 +
            1 +
            " of " +
            brandRecommendedShowProductInfo.length
          }
          lastLabel=" go to detail, button"
          {...rest}
        />
      );
    },
    [brandRecommendedShowProductInfo, contentsIndex, handleClick, handleFocus]
  );

  return (
    <div className={css.container}>
      {brandRecommendedShowProductInfo && (
        <TVirtualGridList
          cbScrollTo={getScrollTo}
          className={css.tVirtualGridList}
          dataSize={brandRecommendedShowProductInfo.length}
          direction="horizontal"
          itemHeight={438}
          itemWidth={324}
          spacing={18}
          renderItem={renderItem}
        />
      )}
    </div>
  );
}
