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,
  scaleH,
} from "../../../../../utils/helperMethods";
import css from "./ShowroomProductList.module.less";

export default function ShowroomProductList({
  handleItemFocus,
  roomThemeProducts,
  selectedPatncNm,
  selectedPatnrId,
  selectedRoomId,
  themeExpsOrd,
  themeId,
  themeNm,
  shelfOrder,
  shelfTitle,
  spotlightId,
}) {
  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(() => {
    if (
      panelInfo?.section !== "showroom" ||
      !panelInfo?.x ||
      panelInfo?.exprOrd !== themeExpsOrd
    ) {
      return;
    }

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

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

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

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

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

      const lastFocusedTarget = Spotlight.getCurrent();

      if (lastFocusedTarget) {
        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 = "showroom";
          const x = getTranslate3dValueByDirection(xContainer);

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

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

      dispatch(
        pushPanel({
          name: panel_names.IMAGE_PANEL,
          panelInfo: {
            patncNm: selectedPatncNm,
            patnrId: selectedPatnrId ?? panelInfo?.patnrId,
            roomId: selectedRoomId,
            targetId: "spotlightId-" + removeDotAndColon(prdtId),
            themeExpsOrd,
            themeId,
            themeNm,
            y,
          },
        })
      );
    },
    [
      dispatch,
      panelInfo?.patnrId,
      selectedPatncNm,
      selectedPatnrId,
      selectedRoomId,
      themeExpsOrd,
      themeId,
      themeNm,
    ]
  );

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

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

  const renderItem = useCallback(
    ({ index, ...rest }) => {
      const {
        offerInfo,
        patnrId,
        prdtExpsOrd,
        prdtId,
        prdtImgUrl,
        prdtNm,
        priceInfo,
        catNm,
        brndNm,
      } = roomThemeProducts[index];

      return (
        <TItemCard
          contextName={LOG_CONTEXT_NAME.FEATURED_BRANDS}
          messageId={LOG_MESSAGE_ID.SHELF_CLICK}
          patnerName={selectedPatncNm}
          shelfLocation={shelfOrder}
          shelfTitle={shelfTitle}
          shelfId={spotlightId}
          contentId={themeId}
          contentTitle={themeNm}
          order={prdtExpsOrd}
          catNm={catNm}
          data-exposure-order={themeExpsOrd}
          imageAlt={prdtNm}
          imageSource={prdtImgUrl}
          onClick={handleClick(patnrId, prdtId, index)}
          onFocus={handleFocus}
          offerInfo={offerInfo}
          priceInfo={priceInfo}
          productId={prdtId}
          productName={prdtNm}
          brandName={brndNm}
          spotlightId={"showroom-spotlightId-" + removeDotAndColon(prdtId)}
          label={index * 1 + 1 + " of " + roomThemeProducts.length}
          lastLabel=" go to detail, button"
          {...rest}
        />
      );
    },
    [handleClick, handleFocus, roomThemeProducts, selectedPatncNm, themeExpsOrd]
  );

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