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

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

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

import {
  sendLogDetail,
  sendLogGNB,
  sendLogProductDetail,
  sendLogShopByMobile,
  sendLogTotalRecommend,
} from "../../../actions/logActions";
import {
  LOG_CONTEXT_NAME,
  LOG_MENU,
  LOG_MESSAGE_ID,
  LOG_TP_NO,
} from "../../../utils/Config";
import {
  formatGMTString,
  formatLocalDateTime,
} from "../../../utils/helperMethods";
import Indicator from "../components/indicator/Indicator";
import IndicatorOptions from "../components/indicator/IndicatorOptions";
import ProductOption from "../components/ProductOption";
import GroupOption from "./GroupOption";
import css from "./GroupProduct.module.less";

const Container = SpotlightContainerDecorator(
  { enterTo: "last-focused", preserveld: true },
  "div"
);
export default function GroupProduct({
  isOnTop,
  panelInfo,
  selectedPatnrId,
  selectedPrdtId,
  selectedIndex,
  setSelectedIndex,
  shopByMobileLogRef,
  isYouMayLikeOpened,
}) {
  const dispatch = useDispatch();

  const productData = useSelector((state) => state.main.productData);
  const nowMenu = useSelector((state) => state.common.menu.nowMenu);

  const entryMenuRef = useRef(null);

  const isProductSoldOut = useMemo(() => {
    if (productData && productData.soldoutFlag === "Y") {
      return true;
    } else {
      return false;
    }
  }, [productData]);

  useEffect(() => {
    if (!entryMenuRef.current) entryMenuRef.current = nowMenu;

    const menu = isYouMayLikeOpened
      ? `${LOG_MENU.DETAIL_PAGE_GROUP_DETAIL}/${LOG_MENU.DETAIL_PAGE_YOU_MAY_LIKE}`
      : LOG_MENU.DETAIL_PAGE_GROUP_DETAIL;

    dispatch(sendLogGNB(menu));
  }, [isYouMayLikeOpened]);

  useEffect(() => {
    if (productData && Object.keys(productData).length > 0) {
      const params = {
        befPrice: productData?.priceInfo?.split("|")[0],
        curationId: productData?.curationId ?? "",
        curationNm: productData?.curationNm ?? "",
        entryMenu: entryMenuRef.current,
        expsOrd: "1",
        inDt: formatGMTString(new Date()),
        lastPrice: productData.priceInfo?.split("|")[1],
        lgCatCd: productData?.catCd ?? "",
        lgCatNm: productData?.catNm ?? "",
        linkTpCd: panelInfo?.linkTpCd ?? "",
        logTpNo: LOG_TP_NO.PRODUCT.GROUP_DETAIL,
        patncNm: productData?.patncNm ?? "",
        patnrId: productData?.patnrId ?? "",
        prdtId: productData?.prdtId ?? "",
        prdtNm: productData?.prdtNm ?? "",
        revwGrd: productData?.revwGrd ?? "",
        rewdAplyFlag: productData.priceInfo?.split("|")[2],
        tsvFlag: productData?.todaySpclFlag ?? "",
      };

      return () => dispatch(sendLogProductDetail(params));
    }
  }, [productData]);

  const handleIndicatorOptions = useCallback(() => {
    if (productData && Object.keys(productData).length > 0) {
      const params = {
        curationId: productData?.curationId ?? "",
        curationNm: productData?.curationNm ?? "",
        inDt: "",
        linkTpCd: panelInfo?.linkTpCd ?? "",
        logTpNo: LOG_TP_NO.DETAIL.DETAIL_BUTTON_CLICK,
        patncNm: productData?.patncNm ?? "",
        patnrId: productData?.patnrId ?? "",
      };

      dispatch(sendLogDetail(params));
      dispatch(
        sendLogTotalRecommend({
          menu: LOG_MENU.DETAIL_PAGE_GROUP_DETAIL,
          buttonTitle: "DESCRIPTION",
          contextName: LOG_CONTEXT_NAME.DETAILPAGE,
          messageId: LOG_MESSAGE_ID.BUTTONCLICK,
        })
      );
    }
  }, [productData]);

  const handleMobileSendPopupOpen = useCallback(() => {
    if (productData && Object.keys(productData).length > 0) {
      const regularPrice = productData?.priceInfo?.split("|")[0];
      const discountPrice = productData?.priceInfo?.split("|")[1];
      const discountRate = productData?.priceInfo?.split("|")[4];
      const logParams = {
        status: "open",
        nowMenu: nowMenu,
        partner: productData?.patncNm,
        productId: productData?.prdtId,
        productTitle: productData?.prdtNm,
        price: discountRate ? discountPrice : regularPrice,
        brand: productData?.brndNm,
        discount: discountRate,
        category: productData?.catNm,
        contextName: LOG_CONTEXT_NAME.SHOPBYMOBILE,
        messageId: LOG_MESSAGE_ID.SMB,
      };
      dispatch(sendLogTotalRecommend(logParams));
      dispatch(
        sendLogTotalRecommend({
          menu: LOG_MENU.DETAIL_PAGE_GROUP_DETAIL,
          buttonTitle: "Shop By Mobile",
          contextName: LOG_CONTEXT_NAME.DETAILPAGE,
          messageId: LOG_MESSAGE_ID.BUTTONCLICK,
        })
      );
    }
    if (productData && Object.keys(productData).length > 0) {
      const params = {
        befPrice: productData?.priceInfo?.split("|")[0],
        curationId: productData?.curationId ?? "",
        curationNm: productData?.curationNm ?? "",
        evntId: "",
        evntNm: "",
        lastPrice: productData?.priceInfo?.split("|")[1],
        lgCatCd: productData?.catCd ?? "",
        lgCatNm: productData?.catNm ?? "",
        liveFlag: panelInfo?.liveFlag ?? "N",
        locDt: formatLocalDateTime(new Date()),
        logTpNo: LOG_TP_NO.SHOP_BY_MOBILE.SHOP_BY_MOBILE,
        mbphNoFlag: "N",
        patncNm: productData?.patncNm,
        patnrId: productData?.patnrId,
        prdtId: productData?.prdtId,
        prdtNm: productData?.prdtNm,
        revwGrd: productData?.revwGrd ?? "",
        rewdAplyFlag: productData?.priceInfo?.split("|")[2],
        shopByMobileFlag: "Y",
        shopTpNm: "product",
        showId: productData?.showId ?? "",
        showNm: productData?.showNm ?? "",
        trmsAgrFlag: "N",
        tsvFlag: productData?.todaySpclFlag ?? "",
      };

      dispatch(sendLogShopByMobile(params));
      shopByMobileLogRef.current = params;
    }
  }, [panelInfo?.liveFlag, productData, shopByMobileLogRef]);

  return (
    <>
      <Container
        className={css.container}
        spotlightId="spotlight-IndicatorContainer"
      >
        <Indicator
          isOnTop={isOnTop}
          launchedFromPlayer={panelInfo?.launchedFromPlayer}
          productInfo={productData}
          selectedIndex={selectedIndex}
          setSelectedIndex={setSelectedIndex}
          soldoutFlag={isProductSoldOut}
        />
        <IndicatorOptions
          handleIndicatorOptions={handleIndicatorOptions}
          handleMobileSendPopupOpen={handleMobileSendPopupOpen}
          isFullOption
          panelInfo={panelInfo}
          productInfo={productData}
          thumbnailUrl={productData.imgUrls600[0]}
        />
      </Container>
      <div>
        <ProductOption productInfo={productData}>
          <GroupOption />
        </ProductOption>
      </div>
    </>
  );
}
