import React, { useCallback, useEffect } from "react";

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

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

import { startVideoPlayer } from "../../../../../actions/playActions";
import TItemCard, {
  removeDotAndColon,
} from "../../../../../components/TItemCard/TItemCard";
import TVirtualGridList from "../../../../../components/TVirtualGridList/TVirtualGridList";
import useScrollTo from "../../../../../hooks/useScrollTo";
import { SpotlightIds } from "../../../../../utils/SpotlightIds";
import css from "./ShowProductContents.module.less";

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

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

  const showProductContentDatas = useSelector(
    (state) => state.main?.topShowInfo
  );
  const showProductCategoryData = useSelector(
    (state) => state.main.subCategoryData.categoryDescInfos
  );

  const { productInfos } = showProductContentDatas || {};

  const { getScrollTo, scrollLeft } = useScrollTo();

  useEffect(() => {
    scrollLeft();
  }, [productInfos]);

  const handleItemClick = useCallback(
    (index, prdtId) => (ev) => {
      const { showId, patnrId, lgCatCd } = showProductContentDatas;
      onClick && onClick(ev);
      dispatch(
        startVideoPlayer({
          targetId: "spotlightId-" + removeDotAndColon(prdtId),
          showId,
          patnrId,
          shptmBanrTpNm: "VOD",
          lgCatCd,
          modal: false,
          index,
        })
      );
    },
    [onClick, showProductContentDatas]
  );

  const renderItem = useCallback(
    ({ index, ...rest }) => {
      const { prdtId, prdtNm, imgUrl, priceInfo, offerInfo } =
        productInfos[index];

      return (
        <TItemCard
          {...rest}
          key={prdtId}
          imageAlt={prdtId}
          imageSource={imgUrl}
          priceInfo={priceInfo}
          productName={prdtNm}
          onClick={handleItemClick(index, prdtId)}
          offerInfo={offerInfo}
          productId={prdtId}
          label={index * 1 + 1 + " of " + productInfos.length}
          lastLabel=" go to detail, button"
          spotlightId={"showCategory-spotlightId-" + removeDotAndColon(prdtId)}
        />
      );
    },
    [showProductContentDatas, handleItemClick]
  );

  return (
    <div className={css.container}>
      {productInfos && productInfos.length > 0 && (
        <TVirtualGridList
          cbScrollTo={getScrollTo}
          spotlightId={SpotlightIds.SHOW_PRODUCTS_BOX}
          className={css.grid}
          itemRenderer={renderItem}
          dataSize={productInfos.length}
          itemWidth={342}
          itemHeight={490}
          spacing={0}
          direction="horizontal"
        />
      )}
    </div>
  );
}
