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

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

import { pushPanel } from "../../../../actions/panelActions";
import TItemCard, { TYPES } from "../../../../components/TItemCard/TItemCard";
import TVirtualGridList from "../../../../components/TVirtualGridList/TVirtualGridList";
import { LOG_MENU, panel_names } from "../../../../utils/Config";
import { $L, scaleH } from "../../../../utils/helperMethods";
import css from "./YouMayLikeContents.module.less";

export default function YouMayLikeContents({
  shopNowInfo,
  handleItemFocus,
  playListInfo,
}) {
  const dispatch = useDispatch();
  const [height, setHeight] = useState(scaleH(236));
  const youmaylikeInfos = useSelector((state) => state.main.youmaylikeInfos);

  const gridStyle = useMemo(() => ({ height: `${height}px` }), [height]);
  useEffect(() => {
    if (shopNowInfo && shopNowInfo.length === 2) {
      setHeight(scaleH(300));
    } else if (shopNowInfo.length <= 0) {
      setHeight(scaleH(500));
    } else {
      setHeight(scaleH(560));
    }
  }, [shopNowInfo, youmaylikeInfos]);

  const handleFocus = useCallback(
    () => () => {
      if (handleItemFocus) {
        handleItemFocus(LOG_MENU.FULL_YOU_MAY_LIKE);
      }
    },
    [handleItemFocus]
  );

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

      const handleItemClick = () => {
        dispatch(
          pushPanel({
            name: panel_names.DETAIL_PANEL,
            panelInfo: {
              showNm: playListInfo?.showNm,
              showId: playListInfo?.showId,
              liveFlag: playListInfo?.liveFlag,
              catDpTh3: playListInfo?.catDpTh3,
              catDpTh4: playListInfo?.catDpTh4,
              patnrId,
              prdtId,
              launchedFromPlayer: true,
            },
          })
        );
      };

      return (
        <TItemCard
          {...rest}
          key={prdtId}
          imageAlt={prdtId}
          imageSource={imgUrl}
          priceInfo={priceInfo}
          offerInfo={offerInfo}
          productName={prdtNm}
          onClick={handleItemClick}
          onFocus={handleFocus()}
          type={TYPES.horizontal}
        />
      );
    },
    [youmaylikeInfos]
  );

  return (
    <>
      {youmaylikeInfos && youmaylikeInfos.length > 0 && (
        <>
          <div className={css.title}>{$L("You may also like")}</div>
          <div className={css.line}></div>

          <TVirtualGridList
            style={gridStyle}
            dataSize={youmaylikeInfos.length}
            direction="vertical"
            renderItem={renderItem}
            itemWidth={600}
            itemHeight={236}
            spacing={12}
            className={css.itemList}
            noScrollByWheel={false}
          />
        </>
      )}
    </>
  );
}
