import React, { memo, useEffect, useRef } from "react";

import { useDispatch, useSelector } from "react-redux";

import { Job } from "@enact/core/util";
import SpotlightContainerDecorator from "@enact/spotlight/SpotlightContainerDecorator";
import {
  getContainerId,
  setContainerLastFocusedElement,
} from "@enact/spotlight/src/container";

import { sendLogFeaturedBrands } from "../../../../actions/logActions";
import TScroller from "../../../../components/TScroller/TScroller";
import useScrollTo from "../../../../hooks/useScrollTo";
import css from "./RecommendedShowsNav.module.less";
import RecommendedShowsNavItem from "./RecommendedShowsNavItem/RecommendedShowsNavItem";

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

export default memo(function RecommendedShowsNav({
  brandRecommendedShowCategoryInfo,
  fromGNB,
  fromQuickMenu,
  handleItemFocus,
  selectedCatCd,
  selectedPatncNm,
  selectedPatnrId,
  setSelectedCatCd,
}) {
  const dispatch = useDispatch();
  const { getScrollTo, scrollLeft } = useScrollTo();

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

  const firstCatCdRef = useRef(
    `${brandRecommendedShowCategoryInfo[0]?.catCd}` || null
  );
  const firstCatNmRef = useRef(
    brandRecommendedShowCategoryInfo[0]?.catNm || null
  );
  const logTimerRef = useRef(null);
  const scrollLeftJob = useRef(new Job((func) => func(), 0));

  useEffect(() => {
    const scrollLeftJobValue = scrollLeftJob.current;

    if (!panelInfo?.recommendedShowsNavX) {
      return;
    }

    const { recommendedShowsNavX } = panelInfo;

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

    return () => {
      if (panelInfo?.recommendedShowsNavX) {
        scrollLeftJobValue.stop();
      }
    };
  }, [panelInfo, scrollLeft]);

  useEffect(() => {
    const containerId = "recommended-shows-nav-id";
    const container = document.getElementById(containerId);

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

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

    scrollLeft();
  }, [scrollLeft, selectedPatnrId]);

  useEffect(() => {
    if (fromGNB || fromQuickMenu) {
      logTimerRef.current = setTimeout(() => {
        dispatch(
          sendLogFeaturedBrands({
            patnrId: selectedPatnrId,
            patncNm: selectedPatncNm,
            catCd: firstCatCdRef.current,
            catNm: firstCatNmRef.current,
          })
        );
      }, 500);

      return () => clearTimeout(logTimerRef.current);
    }
  }, [fromGNB, fromQuickMenu, selectedPatnrId, selectedPatncNm]);

  return (
    <Container
      className={css.nav}
      id="recommended-shows-nav-id"
      spotlightId="recommended-shows-nav-id"
    >
      <TScroller
        cbScrollTo={getScrollTo}
        direction="horizontal"
        noScrollByWheel
      >
        <ul>
          {brandRecommendedShowCategoryInfo.map(
            (brandRecommendedShowCategoryInfoItem, itemIndex, array) => (
              <RecommendedShowsNavItem
                brandRecommendedShowCategoryInfoItem={
                  brandRecommendedShowCategoryInfoItem
                }
                handleItemFocus={handleItemFocus}
                itemIndex={itemIndex}
                itemLength={array.length}
                key={"brand-recommended-show-category-info-" + itemIndex}
                scrollLeft={scrollLeft}
                selectedCatCd={selectedCatCd}
                selectedPatnrId={selectedPatnrId}
                selectedPatncNm={selectedPatncNm}
                setSelectedCatCd={setSelectedCatCd}
              />
            )
          )}
        </ul>
      </TScroller>
    </Container>
  );
});
