import React, {
  useCallback,
  useEffect,
  useRef,
  useState,
} from 'react';

import { useSelector } from 'react-redux';

import VirtualGridList from '@enact/sandstone/VirtualList';
import {
  SpotlightContainerDecorator,
} from '@enact/spotlight/SpotlightContainerDecorator';
import Spottable from '@enact/spotlight/Spottable';

import SectionTitle from '../../../components/SectionTitle/SectionTitle';
import TGrid from '../../../components/TGrid/TGrid';
import {
  $L,
  scaleH,
  scaleW,
} from '../../../utils/helperMethods';
import css from './BestSeller.module.less';
import BestSellerItem from './BestSellerItem/BestSellerItem';

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

const BestSeller = () => {
  const bestSellerDatas = useSelector(
    (state) => state.product.bestSellerData.bestSeller
  );
  const renderItem = useCallback(
    ({ index, ...rest }) => {
      const itemData = bestSellerDatas[index];
      if (index !== bestSellerDatas.length) {
        return (
          <BestSellerItem
            bestSellerData={bestSellerDatas}
            itemData={itemData}
            isBestSeller
            {...rest}
          />
        );
      } else {
        return (
          <SpottableComponent
            className={css.addItem}
            {...rest}
          ></SpottableComponent>
        );
      }
    },
    [bestSellerDatas]
  );

  return (
    <Container className={css.bestSellerWrap}>
      <SectionTitle title={$L(`BEST SELLER`)} />

      <TGrid type="homeBestSeller">
        {bestSellerDatas && bestSellerDatas.length > 0 && (
          <VirtualGridList
            dataSize={bestSellerDatas.length + 1}
            direction="horizontal"
            horizontalScrollbar="hidden"
            itemRenderer={renderItem}
            itemSize={{
              minWidth: scaleW(324),
              minHeight: scaleH(438),
            }}
            noScrollByWheel
            scrollMode="translate"
            spacing={scaleW(24)}
            className={css.grid}
          />
        )}
      </TGrid>
    </Container>
  );
};

export default BestSeller;
