import React, { useCallback } from "react";

import { VirtualGridList } from "@enact/sandstone/VirtualList";
import SpotlightContainerDecorator from "@enact/spotlight/SpotlightContainerDecorator";

import { scaleH, scaleW } from "../../../utils/helperMethods";
import CategoryNavItem from "../CategoryNav/CategoryNavItem/CategoryNavItem";
import css from "./CategoryNav.module.less";

const LIST_ITEM_CONF = {
  ITEM_WIDTH: 210,
  ITEM_HEIGHT: 236,
  SAPCING: 30,
};

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

export default function CategoryNav({
  categoryInfos,
  currentCategoryCode,
  setCurrentCategoryCode,
  ...rest
}) {
  const handleCategoryNavClick = useCallback(
    (categoryCode) => {
      if (currentCategoryCode === categoryCode) {
        return;
      }

      setCurrentCategoryCode(categoryCode);
    },
    [currentCategoryCode]
  );

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

  return (
    <Container className={css.container} {...rest}>
      {categoryInfos && categoryInfos.length > 0 && (
        <VirtualGridList
          className={css.virtualGridList}
          dataSize={categoryInfos.length}
          direction="horizontal"
          horizontalScrollbar="hidden"
          itemRenderer={renderItem}
          itemSize={{
            minWidth: scaleW(LIST_ITEM_CONF.ITEM_WIDTH),
            minHeight: scaleH(LIST_ITEM_CONF.ITEM_HEIGHT),
          }}
          noScrollByWheel
          scrollMode="translate"
          spacing={scaleW(LIST_ITEM_CONF.SAPCING)}
        />
      )}
    </Container>
  );
}
