import React, { useCallback } from 'react';

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

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

import { pushPanel } from '../../../../actions/panelActions';
import TItemCard from '../../../../components/TItemCard/TItemCard';
import { panel_names } from '../../../../utils/Config';
import { SpotlightIds } from '../../../../utils/SpotlightIds';
import NoResultsCategoryItems
  from '../NoResultsCategory/NoResultsCategoryItems';
import css from './ItemContents.module.less';

const Container = SpotlightContainerDecorator({ enterTo: null }, "div");

export default function ItemContents({ onClick }) {
  const dispatch = useDispatch();

  const itemListDatas = useSelector(
    (state) => state.main.subCategoryData?.categoryItemInfos
  );

  const itemListDatasItem = useSelector(
    (state) => state.main.subCategoryData?.categoryItemInfos?.subCatItemList
  );

  const _handleItemClick = useCallback(
    (patnrId, prdtId) => (ev) => {
      onClick && onClick(ev);
      dispatch(
        pushPanel({
          name: panel_names.DETAIL_PANEL,
          panelInfo: {
            patnrId: patnrId,
            prdtId: prdtId,
          },
        })
      );
    },
    [onClick]
  );

  return (
    <>
      <Container
        className={css.container}
        spotlightId={SpotlightIds.CATEGORY_CONTENTS_BOX}
      >
        {itemListDatas &&
          itemListDatasItem.length > 0 &&
          itemListDatasItem.map((item, index) => {
            const { imgUrl, offerInfo, patnrId, prdtId, prdtNm, priceInfo } =
              item;
            return (
              <TItemCard
                key={prdtId}
                imageAlt={prdtId}
                imageSource={imgUrl}
                priceInfo={priceInfo}
                productName={prdtNm}
                productId={prdtId}
                onClick={_handleItemClick(patnrId, prdtId)}
                offerInfo={offerInfo}
                spotlightId={"categoryItemContents" + index}
                label={index * 1 + 1 + " of " + itemListDatas.total}
                lastLabel=" go to detail, button"
                data-wheel-point={index >= 5}
              />
            );
          })}
        {itemListDatas && itemListDatasItem.length === 0 && (
          <NoResultsCategoryItems />
        )}
      </Container>
    </>
  );
}
