import React, { memo, 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 } from "../../../../../utils/helperMethods";
import css from "./LiveChannelsHorizontalProductList.module.less";

export default memo(function LiveChannelsHorizontalProductList({
  brandProductInfo,
  chanId,
  contentsIndex,
  handleItemFocus,
  patnrId,
  selectedPatnrId,
  showId,
  showUrl,
  showNm,
  chanNm,
  shelfOrder,
  shelfTitle,
  shelfId,
  catNm,
  order,
}) {
  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 !== "live-channels-horizontal") {
      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, selectedPatnrId]);

  const handleClick = useCallback(
    (prdtId) => (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 = "live-channels-horizontal";
        const x = getTranslate3dValueByDirection(xContainer);

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

        dispatch(
          startVideoPlayer({
            chanId,
            modal: false,
            patnrId,
            prdtId,
            showId,
            showUrl,
            shptmBanrTpNm: "LIVE",
            targetId: "spotlightId-" + prdtId,
          })
        );
      }
    },
    [chanId, dispatch, patnrId, showId, showUrl]
  );

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

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

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

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

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