import React, { memo, useCallback, useState, useRef } from "react";

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

import SectionTitle from "../../../components/SectionTitle/SectionTitle";
import css from "./OnSaleContents.module.less";
import OnSaleProductList from "./OnSaleProductList/OnSaleProductList";
import { useDispatch, useSelector } from "react-redux";
import { sendLogTotalRecommend } from "../../../actions/logActions";
import { LOG_CONTEXT_NAME, LOG_MESSAGE_ID } from "../../../utils/Config";

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

export default memo(function OnSaleContents({
  contentsIndex,
  isTopButtonClicked,
  saleProductInfos,
  saleNm,
  spotlightId,
  selectedLgCatCd,
  selectedLgCatNm,
  shelfOrder,
  onShelfFocus,
}) {
  const dispatch = useDispatch();

  const onFocus = useCallback(() => {
    // 부모 컴포넌트에서 shelf 포커스
    const shouldDispatch = onShelfFocus ? onShelfFocus(shelfOrder) : true;
    if (shouldDispatch) {
      const params = {
        contextName: LOG_CONTEXT_NAME.ON_SALE,
        messageId: LOG_MESSAGE_ID.SHELF,
        category: selectedLgCatNm,
        shelfLocation: shelfOrder,
        shelfId: selectedLgCatCd,
        shelfTitle: saleNm,
      };
      dispatch(sendLogTotalRecommend(params));
    }
  }, [
    shelfOrder,
    selectedLgCatNm,
    selectedLgCatCd,
    saleNm,
    dispatch,
    onShelfFocus,
  ]);

  return (
    <Container
      className={css.container}
      spotlightId={spotlightId}
      data-wheel-point
      onFocus={onFocus}
    >
      <SectionTitle
        data-title-index={contentsIndex}
        title={saleNm}
        label={saleNm}
      />
      <OnSaleProductList
        contentsIndex={contentsIndex}
        isTopButtonClicked={isTopButtonClicked}
        saleProductInfos={saleProductInfos}
        selectedLgCatCd={selectedLgCatCd}
        selectedLgCatNm={selectedLgCatNm}
        spotlightId={spotlightId}
        shelfOrder={shelfOrder}
        shelfTitle={saleNm}
      />
    </Container>
  );
});
