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 IndicatorOptions from "../components/indicator/IndicatorOptions";
import ThemeIndicator from "../components/indicator/ThemeIndicator";
import ShowSingleOption from "./ShowOptions/ShowSingleOption";
import ShowUnableOption from "./ShowOptions/ShowUnableOption";
import css from "./ShowProduct.module.less";

const Container = SpotlightContainerDecorator(
  { enterTo: "last-focused", preserveld: true },
  "div"
);
export default function ShowOption({
  isOnTop,
  panelInfo,
  launchedFromPlayer,
  selectedIndex,
  selectedCurationId,
  selectedCurationNm,
  // selectedPatnrId,
  setSelectedIndex,
  shopByMobileLogRef,
  isYouMayLikeOpened,
  isLoading,
  logMenu,
}) {
  const dispatch = useDispatch();
  const productInfo = useSelector(
    (state) => state.home.themeCurationDetailInfoData
  );
  const productData = useSelector((state) => state.home.productData);
  const webOSVersion = useSelector(
    (state) => state.common.appStatus.webOSVersion
  );
  const nowMenu = useSelector((state) => state.common.menu.nowMenu);
  const entryMenu = useSelector((state) => state.common.menu.entryMenu);

  const detailLogParamsRef = useRef(null);
  const timerRef = useRef(null);

  const showProductInfo = useMemo(() => {
    if (productData && productInfo) {
      const themeInfo = productData?.themeInfo[0];

      if (themeInfo) {
        const { curationId, curationNm } = themeInfo;

        return {
          ...productInfo[selectedIndex],
          curationId,
          curationNm,
          expsOrd: `${selectedIndex + 1}`,
        };
      }
    }

    return {};
  }, [productData, productInfo, selectedIndex]);

  useEffect(() => {
    const menu = isYouMayLikeOpened
      ? `${LOG_MENU.DETAIL_PAGE_THEME_DETAIL}/${LOG_MENU.DETAIL_PAGE_YOU_MAY_LIKE}`
      : LOG_MENU.DETAIL_PAGE_THEME_DETAIL;

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

  useEffect(() => {
    if (productData && Object.keys(productData).length > 0) {
      const themeInfo = productData?.themeInfo[0];

      const params = {
        curationId: themeInfo?.curationId ?? "",
        curationNm: themeInfo?.curationNm ?? "",
        inDt: formatGMTString(new Date()),
        linkTpCd: panelInfo?.linkTpCd ?? "",
        logTpNo: LOG_TP_NO.DETAIL.THEME_DETAIL,
        patncNm: themeInfo?.productInfos[selectedIndex]?.patncNm ?? "",
        patnrId: themeInfo?.productInfos[selectedIndex]?.patnrId ?? "",
      };

      detailLogParamsRef.current = params;

      dispatch(sendLogDetail(params));
    }
  }, [productData]);

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

      timerRef.current = setTimeout(
        () => dispatch(sendLogProductDetail(params)),
        1000
      );
    }

    return () => clearTimeout(timerRef.current);
  }, [showProductInfo]);

  const isProductSoldOut = () => {
    if (
      productInfo &&
      productInfo.length > selectedIndex &&
      selectedIndex >= 0
    ) {
      return productInfo[selectedIndex]?.soldoutFlag === "Y";
    } else {
      return false;
    }
  };

  const isSoldout = isProductSoldOut();

  const handleIndicatorOptions = useCallback(() => {
    if (productData && Object.keys(productData).length > 0) {
      const params = {
        ...detailLogParamsRef.current,
        inDt: "",
        logTpNo: LOG_TP_NO.DETAIL.DETAIL_BUTTON_CLICK,
      };

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

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

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

  const isBillingProductVisible = useMemo(() => {
    return (
      productInfo &&
      productInfo[selectedIndex]?.pmtSuptYn === "Y" &&
      webOSVersion >= "6.0"
    );
  }, [productData, webOSVersion, selectedIndex]);

  const isUnavailableProductVisible = useMemo(() => {
    return (
      showProductInfo &&
      productInfo &&
      (productInfo[selectedIndex]?.pmtSuptYn === "N" || webOSVersion < "6.0")
    );
  }, [showProductInfo, productInfo, webOSVersion, selectedIndex]);

  return (
    <>
      {productInfo &&
        showProductInfo &&
        Object.keys(showProductInfo).length > 0 && (
          <>
            <Container
              className={css.indicatorContainer}
              spotlightId="spotlight-IndicatorContainer"
            >
              <ThemeIndicator
                themeProductInfos={productInfo}
                themeProductInfo={showProductInfo}
                selectedIndex={selectedIndex}
                setSelectedIndex={setSelectedIndex}
                thumbnailUrls={showProductInfo?.imgUrls600}
                soldoutFlag={isSoldout}
                launchedFromPlayer={launchedFromPlayer}
                isOnTop={isOnTop}
                isLoading={isLoading}
                isSpotlight
              />
              <IndicatorOptions
                handleIndicatorOptions={handleIndicatorOptions}
                handleMobileSendPopupOpen={handleMobileSendPopupOpen}
                isBillingProductVisible={isBillingProductVisible}
                isCall
                isFullOption={showProductInfo?.pmtSuptYn === "Y"}
                isDescription={showProductInfo?.pmtSuptYn !== "Y"}
                thumbnailUrl={showProductInfo?.imgUrls600[0]}
                productInfo={showProductInfo}
              />
            </Container>
            <div className={css.optionContainer}>
              {isBillingProductVisible && (
                <ShowSingleOption
                  productData={productData}
                  productInfo={productInfo}
                  selectedIndex={selectedIndex}
                  soldoutFlag={isSoldout}
                  logMenu={logMenu}
                />
              )}
              {isUnavailableProductVisible && (
                <ShowUnableOption
                  selectedIndex={selectedIndex}
                  setSelectedIndex={setSelectedIndex}
                  productInfo={showProductInfo}
                  productData={productData}
                  selectedCurationId={selectedCurationId}
                  selectedCurationNm={selectedCurationNm}
                  soldoutFlag={isSoldout}
                  handleMobileSendPopupOpen={handleMobileSendPopupOpen}
                  logMenu={logMenu}
                />
              )}
            </div>
          </>
        )}
    </>
  );
}
