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 { panel_names } from "../../../../../utils/Config";
import {
  getTranslate3dValueByDirection,
  scaleH,
} from "../../../../../utils/helperMethods";
import css from "./FeaturedCreatorsProductList.module.less";

export default function FeaturedCreatorsProductList({
  brandCreatorsProductInfo,
  contentsIndex,
  handleItemFocus,
  hstNm,
  patnrId,
  selectedHstNm,
  selectedPatnrId,
  showId,
}) {
  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 !== "featured-creators") {
      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, selectedHstNm, 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 = "featured-creators";
        const x = getTranslate3dValueByDirection(xContainer);

        dispatch(
          updatePanel({
            name: panel_names.FEATURED_BRANDS_PANEL,
            panelInfo: {
              exprOrd,
              hstNm,
              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",
          targetId: "spotlightId-" + prdtId,
          y,
        })
      );
    },
    [dispatch, hstNm, patnrId, showId]
  );

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

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

  const renderItem = useCallback(
    ({ index, ...rest }) => {
      const { offerInfo, prdtId, prdtImgUrl, prdtNm, priceInfo, soldoutFlag } =
        brandCreatorsProductInfo[index];

      return (
        <TItemCard
          data-exposure-order={contentsIndex + 1}
          data-product-card={"featured-creators-product-card-" + contentsIndex}
          imageAlt={prdtNm}
          imageSource={prdtImgUrl}
          onClick={handleClick(prdtId, index)}
          onFocus={handleFocus}
          offerInfo={offerInfo}
          priceInfo={priceInfo}
          productId={prdtId}
          productName={prdtNm}
          soldoutFlag={soldoutFlag}
          spotlightId={
            "featured-creators-spotlightId-" + removeDotAndColon(prdtId)
          }
          {...rest}
        />
      );
    },
    [brandCreatorsProductInfo, contentsIndex, handleClick, handleFocus]
  );

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