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

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

import { Job } from "@enact/core/util";
import SpotlightContainerDecorator from "@enact/spotlight/SpotlightContainerDecorator";
import {
  getContainerNode,
  setContainerLastFocusedElement,
} from "@enact/spotlight/src/container";

import { pushPanel } from "../../../../actions/panelActions";
import TItemCard, { TYPES } from "../../../../components/TItemCard/TItemCard";
import TVirtualGridList from "../../../../components/TVirtualGridList/TVirtualGridList";
import useScrollTo from "../../../../hooks/useScrollTo";
import { LOG_CONTEXT_NAME, LOG_MENU, LOG_MESSAGE_ID, panel_names } from "../../../../utils/Config";
import { scaleH } from "../../../../utils/helperMethods";
import ListEmptyContents from "../TabContents/ListEmptyContents/ListEmptyContents";
import css from "./ShopNowContents.module.less";
import { sendLogTotalRecommend } from "../../../../actions/logActions";


const extractPriceInfo = (priceInfo) => {
  if (!priceInfo) return { originalPrice: "", discountedPrice: "", discountRate: "" };
  
  const parts = priceInfo.split("|").map(part => part.trim());

  return {
    originalPrice: parts[0] || "",
    discountedPrice: parts[1] || "",
    discountRate: parts[4] || ""
  };
};

const Container = SpotlightContainerDecorator(
  { enterTo: "last-focused" },
  "div"
);
export default function ShopNowContents({
  shopNowInfo,
  videoVerticalVisible,
  playListInfo,
  tabIndex,
  handleItemFocus,
  panelInfo,
  tabTitle
}) {
  const { getScrollTo, scrollTop } = useScrollTo();
  const dispatch = useDispatch();
  const paenls = useSelector((state) => state.panels.panels[1]?.panelInfo); 
  const scrollTopJob = useRef(new Job((func) => func(), 0));
  const [height, setHeight] = useState();
  const gridStyle = useMemo(() => ({ height: `${height}px` }), [height]);

  // 각 상품별 가격 정보를 미리 계산
  const priceInfoMap = useMemo(() => {
    if (!shopNowInfo) return {};
    
    const map = {};
    shopNowInfo.forEach((item, index) => {
      if (item.priceInfo) {
        map[index] = extractPriceInfo(item.priceInfo);
      }
    });
    return map;
  }, [shopNowInfo]);

  useEffect(() => {
    return () => {
      const gridListId = "playVideoShopNowBox";
      const girdList = getContainerNode(gridListId);

      if (girdList) setContainerLastFocusedElement(null, [gridListId]);
    };
  }, []);

  useEffect(() => {
    if (!paenls?.y) {
      return;
    }

    const scrollTopJobValue = scrollTopJob.current;
    const { y } = paenls;

    scrollTopJobValue.start(() => scrollTop({ y, animate: false }));

    return () => scrollTopJobValue.stop();
  }, [paenls, scrollTop]);

  useEffect(() => {
    if (shopNowInfo && shopNowInfo.length < 3) {
      return;
    } else if (shopNowInfo && shopNowInfo.length > 3) {
      setHeight(scaleH(956));
    }
  }, [shopNowInfo]);

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

  const renderItem = useCallback(
    ({ index, ...rest }) => {
      const {
        imgUrls,
        patnrId,
        prdtId,
        prdtNm,
        priceInfo,
        offerInfo,
        soldoutFlag,
        patncNm,
        brndNm,
        catNm
      } = shopNowInfo[index];
      
      // 미리 계산된 가격 정보를 사용
      const { originalPrice, discountedPrice, discountRate } = priceInfoMap[index] || {};
      
      const handleItemClick = () => {
        const params = {
          tabTitle: tabTitle[tabIndex],   
          productId: prdtId,
          productTitle: prdtNm,
          partner: patncNm,
          brand: brndNm,
          price: discountRate ? discountedPrice : originalPrice,
          showType: panelInfo?.shptmBanrTpNm,
          category: catNm,
          discount: discountRate,
          contextName: LOG_CONTEXT_NAME.SHOW,
          messageId: LOG_MESSAGE_ID.CONTENTCLICK
        }
        dispatch(sendLogTotalRecommend(params))

        dispatch(
          pushPanel({
            name: panel_names.DETAIL_PANEL,
            panelInfo: {
              showNm: playListInfo?.showNm,
              showId: playListInfo?.showId,
              liveFlag: playListInfo?.liveFlag,
              thumbnailUrl: playListInfo?.thumbnailUrl,
              liveReqFlag: panelInfo?.shptmBanrTpNm === "LIVE" && "Y",
              patnrId,
              prdtId,
              launchedFromPlayer: true,
            },
          })
        );
      };

      return (
        <TItemCard
          {...rest}
          soldoutFlag={soldoutFlag}
          key={prdtId}
          imageAlt={prdtId}
          imageSource={imgUrls[0]}
          priceInfo={priceInfo}
          offerInfo={offerInfo}
          productName={prdtNm}
          productId={prdtId}
          onClick={handleItemClick}
          onFocus={handleFocus()}
          type={TYPES.horizontal}
        />
      );
    },
    [shopNowInfo, videoVerticalVisible, panelInfo?.shptmBanrTpNm, priceInfoMap, tabTitle, tabIndex, playListInfo, dispatch]
  );

  return (
    <>
      <Container className={css.container}>
        {shopNowInfo && shopNowInfo.length > 0 ? (
          <TVirtualGridList
            style={gridStyle}
            cbScrollTo={getScrollTo}
            dataSize={shopNowInfo.length}
            direction="vertical"
            renderItem={renderItem}
            itemWidth={videoVerticalVisible ? 540 : 600}
            itemHeight={236}
            spacing={12}
            className={
              videoVerticalVisible ? css.verticalItemList : css.itemList
            }
            noScrollByWheel={false}
            spotlightId="playVideoShopNowBox"
          />
        ) : (
          <ListEmptyContents tabIndex={tabIndex} />
        )}
      </Container>
    </>
  );
}
