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 SpotlightContainerDecorator from "@enact/spotlight/SpotlightContainerDecorator";
import {
  getContainerId,
  setContainerLastFocusedElement,
} from "@enact/spotlight/src/container";

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 "./FeaturedCategoryProductList.module.less";

const Container = SpotlightContainerDecorator(
  { leaveFor: { right: "" }, enterTo: "last-focused" },
  "div"
);

export default function FeaturedCategoryProductList({
  brandCategoryProductDetailInfo,
  catCd,
  contentsIndex,
  handleItemFocus,
  patnrId,
  selectedCatCdLv1,
  selectedCatCdLv2,
  selectedCategoryLv2Infos,
  selectedPatnrId,
  spotlightId,
  shelfTitle,
  shelfOrder,
  selectedPatncNm,
  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(() => {
    if (
      panelInfo?.section !== "category" ||
      !panelInfo?.x ||
      panelInfo?.exprOrd !== contentsIndex + 1
    ) {
      return;
    }

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

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

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

  useEffect(() => {
    const containerId = "featured-category-product-list-id-" + catCd;
    const container = document.getElementById(containerId);

    if (container) {
      const childrenId = getContainerId(container?.children[0].children[0]);

      if (childrenId) {
        setContainerLastFocusedElement(null, [containerId, childrenId]);
      }
    }

    scrollLeft();
  }, [catCd, scrollLeft, selectedCatCdLv1, selectedCatCdLv2, 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 catCdLv1 = selectedCategoryLv2Infos
          ? selectedCategoryLv2Infos.length > 0
            ? selectedCatCdLv1
            : catCd
          : null;
        const catCdLv2 = selectedCatCdLv2;
        const section = "category";
        const x = getTranslate3dValueByDirection(xContainer);

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

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

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

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

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

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

  return (
    <Container
      className={css.container}
      id={"featured-category-product-list-id-" + catCd}
      spotlightId={"featured-category-product-list-id-" + catCd}
    >
      {brandCategoryProductDetailInfo && (
        <TVirtualGridList
          cbScrollTo={getScrollTo}
          className={css.tVirtualGridList}
          dataSize={brandCategoryProductDetailInfo.length}
          direction="horizontal"
          itemHeight={438}
          itemWidth={324}
          spacing={18}
          renderItem={renderItem}
        />
      )}
    </Container>
  );
}
