import React, { useCallback } from "react";

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

import TVirtualGridList from "../../../../components/TVirtualGridList/TVirtualGridList";
import useScrollReset from "../../../../hooks/useScrollReset";
import useScrollTo from "../../../../hooks/useScrollTo";
import CategoryNavItem from "../CategoryNav/CategoryNavItem/CategoryNavItem";
import css from "./CategoryNav.module.less";

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

export default function CategoryNav({
  categoryInfos,
  currentCategoryCode,
  onCategoryNavClick,
  handleItemFocus,
  ...rest
}) {
  const { scrollLeft } = useScrollTo();
  const { handleScrollReset } = useScrollReset(scrollLeft, true);

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

      if (index === 0) {
        handleScrollReset();
      }
    },
    [handleItemFocus]
  );

  const renderItem = useCallback(
    ({ index, ...rest }) => {
      return (
        <CategoryNavItem
          categoryInfos={categoryInfos}
          currentCategoryCode={currentCategoryCode}
          onCategoryNavClick={onCategoryNavClick}
          index={index}
          onFocus={handleFocus(index)}
          {...rest}
        />
      );
    },
    [categoryInfos, currentCategoryCode, onCategoryNavClick, handleFocus]
  );

  return (
    <Container className={css.container} {...rest}>
      {categoryInfos && categoryInfos.length > 0 && (
        <TVirtualGridList
          className={css.tVirtualGridList}
          dataSize={categoryInfos.length}
          direction="horizontal"
          itemHeight={210}
          itemWidth={215}
          spacing={30}
          renderItem={renderItem}
        />
      )}
    </Container>
  );
}
