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

import SpotlightContainerDecorator from "@enact/spotlight/SpotlightContainerDecorator";

import TScroller from "../../../components/TScroller/TScroller";
import useScrollTo from "../../../hooks/useScrollTo";
import { scaleW } from "../../../utils/helperMethods";
import QuickMenuItem from "../QuickMenu/QuickMenuItem/QuickMenuItem";
import css from "./QuickMenu.module.less";

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

const QuickMenu = ({
  brandInfo,
  fromGNB,
  fromQuickMenu,
  handleItemFocus,
  panelPatnrId,
  selectedPatnrId,
  spotlightId,
  resetStates,
}) => {
  const { getScrollTo, scrollLeft } = useScrollTo();

  const ulRef = useRef(null);

  useEffect(() => {
    if (fromGNB && !fromQuickMenu) {
      const container = ulRef.current;
      const item = document.querySelector(
        `[data-spotlight-id="spotlightId-${panelPatnrId}"]`
      );

      if (container && item) {
        const containerRect = container.getBoundingClientRect();
        const containerWidth = containerRect.width;
        const padding = parseInt(
          window.getComputedStyle(container).getPropertyValue("padding-left")
        );
        const gap = 12;

        const itemRect = item.getBoundingClientRect();
        const itemWidth = itemRect.width;
        const offsetFromContainerLeft = itemRect.left;

        const displayOrder = Array.from(container.children).indexOf(item) + 1;

        const maxVisibleCount = Math.floor(containerWidth / itemWidth);

        const clippedWidht =
          containerWidth - padding - itemWidth * maxVisibleCount + gap;

        let x = 0;

        if (displayOrder > maxVisibleCount) {
          x = scaleW(offsetFromContainerLeft - containerWidth + clippedWidht);
        }

        scrollLeft({ x });
      }
    }
  }, [fromGNB, fromQuickMenu, panelPatnrId, scrollLeft]);

  const _handleItemFocus = useCallback(() => {
    if (handleItemFocus) handleItemFocus(spotlightId);
  }, [handleItemFocus]);

  return (
    <Container className={css.nav} spotlightId={spotlightId} data-wheel-point>
      <TScroller
        cbScrollTo={getScrollTo}
        direction="horizontal"
        noScrollByWheel
      >
        <ul ref={ulRef}>
          {brandInfo.map((brandInfoItem, itemIndex) => (
            <QuickMenuItem
              brandInfoItem={brandInfoItem}
              itemIndex={itemIndex}
              handleItemFocus={_handleItemFocus}
              key={"brand-info" + itemIndex}
              resetStates={resetStates}
              scrollLeft={scrollLeft}
              selectedPatnrId={selectedPatnrId}
              label={itemIndex * 1 + 1 + " of " + brandInfo.length}
            />
          ))}
        </ul>
      </TScroller>
    </Container>
  );
};

export default memo(QuickMenu);
