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

import { useDispatch } from "react-redux";

import Spotlight from "@enact/spotlight";

import { pushPanel, updatePanel } from "../../../../../../actions/panelActions";
import TItemCard from "../../../../../../components/TItemCard/TItemCard";
import {
  LOG_CONTEXT_NAME,
  LOG_MESSAGE_ID,
  panel_names,
} from "../../../../../../utils/Config";
import css from "./FeaturedCategoryProductGridItem.module.less";

const FeaturedCategoryProductGridItem = ({
  brandCategoryProductDetailInfoItem,
  catCd,
  contentsIndex,
  handleItemFocus,
  itemIndex,
  patnrId,
  selectedCatCdLv1,
  selectedCatCdLv2,
  selectedCategoryLv2Infos,
  selectedPatncNm,
  spotlightId,
  shelfOrder,
  shelfTitle,
  catNm,
}) => {
  const dispatch = useDispatch();

  const { imgUrl, offerInfo, prdtId, prdtNm, priceInfo, expsOrd } =
    brandCategoryProductDetailInfoItem;

  const handleClick = useCallback(() => {
    const lastFocusedTarget = Spotlight.getCurrent();
    const lastFocusedTargetId =
      lastFocusedTarget?.getAttribute("data-spotlight-id");

    if (lastFocusedTargetId) {
      const catCdLv1 = selectedCategoryLv2Infos
        ? selectedCategoryLv2Infos.length > 0
          ? selectedCatCdLv1
          : catCd
        : null;
      const catCdLv2 = selectedCatCdLv2;
      const section = "category";
      const x = 0;

      dispatch(
        updatePanel({
          name: panel_names.FEATURED_BRANDS_PANEL,
          panelInfo: {
            catCdLv1,
            catCdLv2,
            lastFocusedTargetId,
            section,
            x,
          },
        })
      );
    }

    dispatch(
      pushPanel({
        name: panel_names.DETAIL_PANEL,
        panelInfo: { patnrId, prdtId },
      })
    );
  }, [
    catCd,
    dispatch,
    patnrId,
    prdtId,
    selectedCatCdLv1,
    selectedCatCdLv2,
    selectedCategoryLv2Infos,
  ]);

  const handleFocus = useCallback(() => {
    if (handleItemFocus) handleItemFocus();

    if (itemIndex > 4) return;
  }, [handleItemFocus, itemIndex]);

  return (
    <li className={css.item}>
      <TItemCard
        contextName={LOG_CONTEXT_NAME.FEATURED_BRANDS}
        messageId={LOG_MESSAGE_ID.SHELF_CLICK}
        catNm={catNm}
        patnerName={selectedPatncNm}
        order={expsOrd}
        shelfLocation={shelfOrder}
        shelfTitle={shelfTitle}
        shelfId={spotlightId}
        data-wheel-point={itemIndex >= 5}
        imageAlt={prdtNm}
        imageSource={imgUrl}
        onClick={handleClick}
        onFocus={handleFocus}
        offerInfo={offerInfo}
        priceInfo={priceInfo}
        productId={prdtId}
        productName={prdtNm}
        label={
          contentsIndex * 1 +
          1 +
          " of " +
          brandCategoryProductDetailInfoItem.length
        }
        lastLabel=" go to detail, button"
        spotlightId={`${spotlightId}-${itemIndex}`}
      />
    </li>
  );
};

export default memo(FeaturedCategoryProductGridItem);
