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 { pushPanel, updatePanel } from "../../../../../actions/panelActions";
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 "./SeriesProductList.module.less";

export default function SeriesProductList({
  brandSeriesProductInfo,
  contentsIndex,
  handleFocus,
  patnrId,
  selectedPatnrId,
  selectedSeriesId,
  selectedPatnrNm,
  shelfOrder,
  shelfTitle,
  spotlightId,
}) {
  const { getScrollTo, scrollLeft } = useScrollTo();

  const dispatch = useDispatch();

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

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

  useEffect(() => {
    if (
      panelInfo?.section !== "series" ||
      !panelInfo?.x ||
      panelInfo?.exprOrd !== contentsIndex + 1
    ) {
      return;
    }

    const scrollLeftJobValue = scrollLeftJob.current;
    const { x } = panelInfo;

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

    return () => scrollLeftJobValue.stop();
  }, [panelInfo, scrollLeft, contentsIndex]);

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

  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 = "series";
        const x = getTranslate3dValueByDirection(xContainer);

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

      dispatch(
        pushPanel({
          name: panel_names.DETAIL_PANEL,
          panelInfo: { patnrId, prdtId },
        })
      );
    },
    [dispatch, patnrId]
  );

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

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

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