import React, { useCallback } from 'react';

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

import { VirtualGridList } from '@enact/sandstone/VirtualList';
import {
  SpotlightContainerDecorator,
} from '@enact/spotlight/SpotlightContainerDecorator';
import ri from '@enact/ui/resolution';

import SectionTitle from '../../../components/SectionTitle/SectionTitle';
import { $L } from '../../../utils/helperMethods';
import css from './HomeOnSale.module.less';
import HomeOnSaleItem from './HomeOnSaleItem/HomeOnSaleItem';

const SALE_ITEM_CONF = {
  ITEM_WIDTH: 630 * 2,
  ITEM_HEIGHT: 300 * 2,
  SPACING: 18 * 2,
};

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

const HomeOnSale = ({ ...rest }) => {
  const dispatch = useDispatch();
  const homeOnSaleInfos = useSelector(
    (state) => state.onSale.onSaleData.homeOnSaleInfos
  );

  const renderItem = useCallback(
    ({ index, ...rest }) => {
      const itemData = homeOnSaleInfos[index];

      return (
        <HomeOnSaleItem
          {...rest}
          key={index}
          homeOnSaleInfos={homeOnSaleInfos}
          itemData={itemData}
        />
      );
    },
    [homeOnSaleInfos]
  );

  return (
    <Container {...rest} className={css.container}>
      <div className={css.bestSeller}>
        <SectionTitle className={css.subTitle} title={$L(`ON SALE`)} />
        <div className={css.onSaleItem}>
          {homeOnSaleInfos && homeOnSaleInfos.length > 0 && (
            <VirtualGridList
              className={css.grid}
              dataSize={homeOnSaleInfos.length}
              direction="horizontal"
              horizontalScrollbar="hidden"
              itemRenderer={renderItem}
              itemSize={{
                minWidth: ri.scale(SALE_ITEM_CONF.ITEM_WIDTH),
                minHeight: ri.scale(SALE_ITEM_CONF.ITEM_HEIGHT),
              }}
              noScrollByWheel
              scrollMode="translate"
              spacing={ri.scale(SALE_ITEM_CONF.SPACING)}
            />
          )}
        </div>
      </div>
    </Container>
  );
};

export default HomeOnSale;
