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

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

import { log } from "@enact/core/handle";
import Spotlight from "@enact/spotlight";
import SpotlightContainerDecorator from "@enact/spotlight/SpotlightContainerDecorator";
import Spottable from "@enact/spotlight/Spottable";

import { getMyInfoCheckoutInfo } from "../../../actions/checkoutActions";
import {
  changeAppStatus,
  launchMembershipApp,
  setHidePopup,
  setShowPopup,
  showError,
} from "../../../actions/commonActions";
import {
  getProductCouponDownload,
  getProductCouponSearch,
  getProductCouponTotDownload,
} from "../../../actions/couponActions";
import {
  sendLogPaymentEntry,
  sendLogTotalRecommend,
} from "../../../actions/logActions";
import { pushPanel } from "../../../actions/panelActions";
import {
  getProductOption,
  getProductOptionId,
} from "../../../actions/productActions";
import TButton from "../../../components/TButton/TButton";
import TPopUp from "../../../components/TPopUp/TPopUp";
import TQRCode from "../../../components/TQRCode/TQRCode";
import TScroller from "../../../components/TScroller/TScroller";
import TVirtualGridList from "../../../components/TVirtualGridList/TVirtualGridList";
import usePriceInfo from "../../../hooks/usePriceInfo";
import * as Config from "../../../utils/Config";
import { $L, getQRCodeUrl } from "../../../utils/helperMethods";
import { SpotlightIds } from "../../../utils/SpotlightIds";
import FavoriteBtn from "../components/FavoriteBtn";
import BillingProductPrice from "./BillingProductPrice/BillingProductPrice";
import css from "./SingleOption.module.less";

const Container = SpotlightContainerDecorator(
  { enterTo: "default-element" },
  "div"
);
const ContainerLF = SpotlightContainerDecorator(
  { enterTo: "last-focused" },
  "div"
);
const SpottableComponent = Spottable("div");

const promotionDesc = $L("Coupon only applicable to this product!");
export default function SingleOption({
  patncNm,
  productInfo,
  isSpotlight,
  selectedPatnrId,
  selectedPrdtId,
  selectedIndex,
  logMenu,
  type,
}) {
  const dispatch = useDispatch();
  const productOptionInfos = useSelector((state) => state.product.prdtOptInfo);
  const productData = useSelector((state) => state.main.productData);
  const { partnerCoupon } = useSelector(
    (state) => state.coupon.productCouponSearchData
  );
  const { popupVisible, activePopup } = useSelector(
    (state) => state.common.popup
  );
  const { userId, userNumber } = useSelector(
    (state) => state.common.appStatus.loginUserData
  );

  const [hasProductOptionArray, setHasProductOptionArray] = useState(true);
  const [promotions, setPromotions] = useState([]);
  const [selectedBtnOptIdx, setSelectedBtnOptIdx] = useState(0);
  const [quantity, setQuantity] = useState(1);
  const [selectedCouponIndex, setSelectedCouponIndex] = useState(0);
  const [selectedCoupon, setSelectedCoupon] = useState();
  const [isOptionValue, setIsOptionValue] = useState(false);
  const [isOptionSelect, setIsOptionSelect] = useState(false);
  const [selectedOptionItemIndex, setSelectedOptionItemIndex] = useState(0);
  const [selectedOptions, setSelectedOptions] = useState();
  const [couponTypes, setCouponTypes] = useState(null);
  const [couponCodes, setCouponCodes] = useState("");
  const [selectedOptionInfo, setSelectedOptionInfo] = useState();
  const [downloadCouponArr, setDownloadCouponArr] = useState([]);
  const [prdtData, setPrdtData] = useState({});
  const [focused, setFocused] = useState(false);
  const [favoriteFlag, setFavoriteFlag] = useState(productInfo?.favorYn);

  const webOSVersion = useSelector(
    (state) => state.common.appStatus.webOSVersion
  );
  const serverHOST = useSelector((state) => state.common.appStatus.serverHOST);
  const serverType = useSelector((state) => state.localSettings.serverType);
  const nowMenu = useSelector((state) => state.common.menu.nowMenu);
  const entryMenu = useSelector((state) => state.common.menu.entryMenu);
  const deviceInfo = useSelector((state) => state.device.deviceInfo);

  const { detailBuyNowUrl } = useMemo(() => {
    return getQRCodeUrl({
      serverHOST,
      serverType,
      prdtData,
      entryMenu,
      nowMenu,
      prdtId: selectedPrdtId,
      patnrId: selectedPatnrId,
      index: deviceInfo?.dvcIndex,
    });
  }, [
    serverHOST,
    serverType,
    prdtData,
    nowMenu,
    entryMenu,
    deviceInfo,
    deviceInfo,
  ]);

  useEffect(() => {
    const params = {
      patnrId: selectedPatnrId,
      prdtId: selectedPrdtId,
      prodOptCdCval: selectedOptions?.prodOptCdCval || "",
      prodQty: quantity,
    };

    setPrdtData(params);
  }, [selectedPatnrId, selectedPrdtId, selectedOptions, quantity]);

  const logInfo = useMemo(() => {
    if (productData) {
      let couponInfo;

      if (partnerCoupon && partnerCoupon.length > 0) {
        couponInfo = partnerCoupon[0];
      }

      const { catCd, catNm, patncNm, patnrId, prdtId, prdtNm, priceInfo } =
        productData;
      const { cpnSno, cpnTtl } = couponInfo || {};
      const prodOptSno =
        (productOptionInfos &&
          productOptionInfos.length > 0 &&
          productOptionInfos[0]?.prodOptSno) ||
        "";
      const prodOptTpCdCval =
        (productOptionInfos &&
          productOptionInfos.length > 0 &&
          productOptionInfos[0]?.prodOptTpCdCval) ||
        "";

      return {
        cpnSno: String(cpnSno) ?? "",
        cpnTtl: cpnTtl ?? "",
        dcAftrPrc: priceInfo.split("|")[1],
        dcBefPrc: priceInfo.split("|")[0],
        lgCatCd: catCd ?? "",
        lgCatNm: catNm ?? "",
        patncNm,
        patnrId,
        prodId: prdtId,
        prodNm: prdtNm,
        prodOptSno: prodOptSno,
        prodOptTpCdCval: prodOptTpCdCval,
        qty: String(quantity),
      };
    }

    return {};
  }, [partnerCoupon, productData, productOptionInfos, quantity]);

  useEffect(() => {
    const newPromotions = [];
    if (partnerCoupon && partnerCoupon.length > 0) {
      newPromotions.push($L("SPECIAL PROMOTION"));
    }
    setPromotions(newPromotions);
  }, [partnerCoupon]);

  useEffect(() => {
    dispatch(
      getProductOption({
        patnrId: selectedPatnrId,
        prdtId: selectedPrdtId,
      })
    );

    dispatch(
      getProductCouponSearch({
        patnrId: selectedPatnrId,
        prdtId: selectedPrdtId,
        mbrNo: userNumber,
      })
    );
  }, [dispatch, selectedPatnrId, selectedPrdtId]);

  useEffect(() => {
    if (type !== "theme") {
      return;
    }

    setSelectedOptions();
    setIsOptionValue(false);
    setSelectedOptionItemIndex(0);
    setIsOptionSelect(false);
    setQuantity(1);
    setSelectedBtnOptIdx(0);
  }, [selectedIndex, productOptionInfos, type]);

  useEffect(() => {
    if (
      productOptionInfos &&
      selectedBtnOptIdx >= 0 &&
      productOptionInfos[selectedBtnOptIdx]?.prdtOptDtl.length === 1 &&
      !isOptionValue
    ) {
      setSelectedOptions(productOptionInfos[selectedBtnOptIdx]?.prdtOptDtl[0]);
      setIsOptionValue(true);
    }
  }, [productOptionInfos, selectedBtnOptIdx, isOptionValue]);

  const onClose = useCallback(
    (spotlightId) => {
      dispatch(setHidePopup());

      let currentSpot;
      if (typeof spotlightId === "string") {
        currentSpot = spotlightId;
      } else {
        currentSpot = SpotlightIds.DETAIL_BUYNOW;
      }

      if (currentSpot) {
        setTimeout(() => {
          Spotlight.focus(currentSpot);
        });
      }
    },
    [dispatch]
  );

  //첫번째 옵션 선택 함수
  const handleOptionClick = useCallback(
    (optionValIdx) => {
      setSelectedBtnOptIdx(optionValIdx);
      setSelectedOptionItemIndex(0);
      setSelectedOptions(productOptionInfos[optionValIdx]?.prdtOptDtl[0]);
      setIsOptionValue(false);
      setIsOptionSelect(true);
      onClose("selectedOptionBox-1");
    },
    [productOptionInfos, selectedOptionItemIndex]
  );

  // 두번째 옵션 선택 함수
  const handleOptionItemClick = useCallback(
    (index) => {
      setSelectedOptionItemIndex(index);
      setSelectedOptions(
        productOptionInfos[selectedBtnOptIdx]?.prdtOptDtl[index]
      );
      dispatch(
        getProductOptionId(
          productOptionInfos[selectedBtnOptIdx]?.prdtOptDtl[index]
            ?.prodOptCdCval
        )
      );
      setIsOptionValue(true);
      onClose();
    },
    [productOptionInfos, selectedBtnOptIdx]
  );

  const hasOnClose = useMemo(() => {
    if (productOptionInfos && productOptionInfos.length > 0) {
      // if ((!isOptionValue && isOptionSelect) || !selectedOptions) {
      return true;
      // }
    }

    return false;
  }, [productOptionInfos, isOptionValue, isOptionSelect, selectedOptions]);

  const loginPopupText = useMemo(() => {
    if (!userNumber) {
      return $L("Would you like to sign in?");
    }
    if (hasOnClose) {
      return $L("Please select Option");
    }
    return $L("Would you like to sign in?");
  }, [hasOnClose, userNumber]);

  const handleIncrement = useCallback(() => {
    setQuantity(quantity + 1);
  }, [quantity]);

  const handlDecrement = useCallback(() => {
    if (quantity <= 1) setQuantity(1);
    else setQuantity(quantity - 1);
  }, [quantity]);

  const handleOptionPopUpOpen = useCallback(
    (optionInfo, isProductOptionInfoArray) => () => {
      if (
        productOptionInfos.length !== 1 &&
        !isOptionSelect &&
        !isProductOptionInfoArray
      ) {
        return dispatch(setShowPopup(Config.ACTIVE_POPUP.loginPopup));
      }

      setSelectedOptionInfo(optionInfo);
      setHasProductOptionArray(isProductOptionInfoArray);
      dispatch(setShowPopup(Config.ACTIVE_POPUP.optionPopup));
    },
    [
      dispatch,
      isOptionSelect,
      activePopup,
      productOptionInfos,
      selectedOptionItemIndex,
      selectedBtnOptIdx,
    ]
  );

  const handleLoginPopUpOpen = useCallback(() => {
    if (!userNumber) {
      if (webOSVersion >= "6.0") {
        setTimeout(() => {
          Spotlight.focus(SpotlightIds.DETAIL_BUYNOW);
        });

        dispatch(setHidePopup());
        dispatch(launchMembershipApp());
      } else {
        dispatch(setShowPopup(Config.ACTIVE_POPUP.qrPopup));
      }
      return;
    }

    if (hasOnClose) {
      dispatch(setHidePopup());

      let spotlightId = "selectedOptionBox-0";

      //옵션이 하나만 있는경우 isOptionValue === false
      if (!isOptionValue) {
        spotlightId = "selectedOptionBox-1";
      }
      setTimeout(() => {
        Spotlight.focus(spotlightId);
      }, 100);
      return;
    }
  }, [dispatch, hasOnClose, isOptionValue, webOSVersion, userNumber]);

  useEffect(() => {
    if (activePopup === Config.ACTIVE_POPUP.optionPopup) {
      const optionTimeOut = setTimeout(() => {
        Spotlight.focus(
          `selectedOptionBtn-${
            hasProductOptionArray ? selectedBtnOptIdx : selectedOptionItemIndex
          }`
        );
      });

      return () => {
        clearTimeout(optionTimeOut);
      };
    }
  }, [activePopup, selectedBtnOptIdx, selectedOptionItemIndex]);

  function checkOutValidate(response) {
    if (response) {
      if (response.retCode === 0) {
        if (
          response.data.cardInfo === null ||
          response.data.billingAddressList.length === 0 ||
          response.data.shippingAddressList.length === 0
        ) {
          dispatch(setShowPopup(Config.ACTIVE_POPUP.qrPopup));
          dispatch(changeAppStatus({ isLoading: false }));

          return;
        } else {
          const { mbrId, prdtId, prodSno } = response.data.productList[0];
          const cartTpSno = `${mbrId}_${prdtId}_${prodSno}`;

          dispatch(
            pushPanel({
              name: Config.panel_names.CHECKOUT_PANEL,
              panelInfo: { logInfo: { ...logInfo, cartTpSno } },
            })
          );

          dispatch(sendLogPaymentEntry({ ...logInfo, cartTpSno }));
        }
      } else if (response.retCode === 1001) {
        dispatch(setShowPopup(Config.ACTIVE_POPUP.qrPopup));
        dispatch(changeAppStatus({ isLoading: false }));
      } else {
        dispatch(
          showError(
            response.retCode,
            response.retMsg,
            false,
            response.retDetailCode,
            response.returnBindStrings
          )
        );
        dispatch(changeAppStatus({ isLoading: false }));

        return;
      }
    }

    Spotlight.focus(SpotlightIds.TPOPUP);
  }

  const handleClickBuyNow = useCallback(() => {
    const optionName = renderOptionName();
    const optionValueName = renderOptionValue();

    if (productInfo && productInfo?.soldoutFlag === "Y") {
      return;
    }
    if (!userNumber || userNumber === "") {
      return dispatch(setShowPopup(Config.ACTIVE_POPUP.loginPopup));
    }

    if (
      productOptionInfos &&
      productOptionInfos.length > 0 &&
      (optionName === "SELECT" || optionValueName === "SELECT")
    ) {
      return dispatch(setShowPopup(Config.ACTIVE_POPUP.loginPopup));
    }
    if (userNumber && selectedPatnrId && selectedPrdtId && quantity) {
      const { prodOptCval, priceInfo } = selectedOptions || {};
      const { patncNm, brndNm, catNm, prdtNm, prdtId, showId, showNm } =
        productInfo;
      const regularPrice = priceInfo?.split("|")[0];
      const discountPrice = priceInfo?.split("|")[1];
      const discountRate = priceInfo?.split("|")[4];
      dispatch(
        sendLogTotalRecommend({
          nowMenu: nowMenu,
          productId: prdtId,
          productTitle: prdtNm,
          partner: patncNm,
          price: discountRate ? discountPrice : regularPrice,
          discount: discountRate,
          brand: brndNm,
          productOption: prodOptCval,
          category: catNm,
          contextName: Config.LOG_CONTEXT_NAME.DETAILPAGE,
          messageId: Config.LOG_MESSAGE_ID.BUY_NOW,
          showId: showId ?? "",
          showNm: showNm ?? "",
        })
      );
      dispatch(
        getMyInfoCheckoutInfo(
          {
            mbrNo: userNumber,
            dirPurcSelYn: "Y",
            cartList: [
              {
                patnrId: selectedPatnrId,
                prdtId: selectedPrdtId,
                prodOptCdCval: selectedOptions?.prodOptCdCval
                  ? selectedOptions.prodOptCdCval
                  : null,
                prodQty: quantity,
                prodOptTpCdCval: productOptionInfos[0]?.prodOptTpCdCval,
              },
            ],
          },
          checkOutValidate
        )
      );
    }
  }, [
    dispatch,
    userNumber,
    selectedPatnrId,
    selectedPrdtId,
    productInfo,
    selectedOptions,
    productOptionInfos,
    quantity,
    checkOutValidate,
  ]);

  const handleCouponClick = useCallback(
    (idx, promotion) => {
      if (!userNumber) {
        dispatch(setShowPopup(Config.ACTIVE_POPUP.loginPopup));
        return;
      }
      if (promotion === "SPECIAL PROMOTION") {
        setSelectedCoupon(partnerCoupon);
      }
      setCouponTypes(idx);
      dispatch(setShowPopup(Config.ACTIVE_POPUP.couponPopup));
    },
    [dispatch, popupVisible, promotions, userNumber]
  );

  const handleCouponTotDownload = useCallback(() => {
    if (selectedCoupon && userNumber) {
      const couponCodesArray = couponCodes
        .split(",")
        .map((code) => parseInt(code.trim()));
      setDownloadCouponArr((prevArr) => [...prevArr, ...couponCodesArray]);

      dispatch(
        getProductCouponTotDownload({
          mbrNo: userNumber,
          cpnSnoAll: couponCodes,
        })
      );
    }
  }, [dispatch, selectedCoupon, userNumber, couponCodes]);

  useEffect(() => {
    if (selectedCoupon) {
      getCouponCode();
    }
  }, [selectedCoupon]);

  //디테일패널 최초 진입시 옵션이 있으면 포커스 없으면 백버튼 포커스
  useEffect(() => {
    if (!isSpotlight) {
      return;
    }

    if (productInfo.optProdYn === "N") {
      Spotlight.focus(SpotlightIds.DETAIL_BUYNOW);
    } else if (productOptionInfos && productOptionInfos.length > 0) {
      Spotlight.focus("selectedOptionBox-0");
      if (productOptionInfos.length === 1) {
        Spotlight.focus("selectedOptionBox-1");
      }
      return;
    }
  }, [productOptionInfos, productInfo]);

  const getCouponCode = () => {
    const snoArray = [];

    for (let i = 0; i < selectedCoupon.length; i++) {
      snoArray.push(selectedCoupon[i].cpnSno);
    }

    setCouponCodes(snoArray.join(", "));
  };

  const renderOptionName = useCallback(() => {
    if (selectedOptions) {
      return productOptionInfos[selectedBtnOptIdx]?.optNm || null;
    }

    return $L("SELECT");
  }, [productOptionInfos, selectedOptions, selectedBtnOptIdx]);

  const renderOptionValue = useCallback(() => {
    if (
      productOptionInfos &&
      productOptionInfos[selectedBtnOptIdx] &&
      productOptionInfos[selectedBtnOptIdx]?.prdtOptDtl &&
      productOptionInfos[selectedBtnOptIdx]?.prdtOptDtl.length > 0 &&
      isOptionValue
    ) {
      return (
        productOptionInfos[selectedBtnOptIdx]?.prdtOptDtl[
          selectedOptionItemIndex
        ]?.prodOptCval || null
      );
    }
    return $L("SELECT");
  }, [
    productOptionInfos,
    selectedBtnOptIdx,
    isOptionValue,
    selectedOptionItemIndex,
  ]);

  const onSpotlightLeftCoupon = () => {
    Spotlight.focus("spotlight-IndicatorContainer");
  };

  useEffect(() => {
    setFavoriteFlag(productInfo?.favorYn ? productInfo?.favorYn : "N");
  }, [productInfo]);

  const onFavoriteFlagChanged = useCallback((ev) => {
    setFavoriteFlag(ev);
  }, []);

  const renderItem = useCallback(
    ({ index, ...rest }) => {
      const {
        cpnDctrt,
        cpnTtl,
        cpnAplyMinPurcAmt,
        cpnAplyMaxDcAmt,
        cpnAplyStrtDtt,
        cpnAplyEndDtt,
        shptmDcTpCd,
        currSign,
        downloadYn,
        cpnSno,
        dcAmt,
      } = selectedCoupon[index];

      const couponAplyStartDate = cpnAplyStrtDtt.split(" ")[0];
      const couponAplyEndDate = cpnAplyEndDtt.split(" ")[0];

      const onFocus = (index) => {
        setSelectedCouponIndex(index);
        setFocused(true);
      };

      const onBlur = () => {
        setFocused(false);
      };

      const handleDownloadClick = () => {
        if (
          downloadCouponArr.length > 0 &&
          downloadCouponArr.includes(cpnSno)
          // downloadYn === "N"
        ) {
          return;
        }
        setDownloadCouponArr((prevArr) => [...prevArr, cpnSno]);
        dispatch(
          getProductCouponDownload({ mbrNo: userNumber, cpnSno: cpnSno })
        );
      };

      return (
        <SpottableComponent
          className={css.couponContainer}
          spotlightid={`spotlightId-coupon-${index}`}
          {...rest}
          onFocus={() => onFocus(index)}
          onBlur={onBlur}
          onClick={handleDownloadClick}
        >
          <div
            className={css.couponItem}
            aria-label={
              "Purchase over " +
              cpnAplyMinPurcAmt +
              "up to " +
              cpnAplyMaxDcAmt +
              " off"
            }
          >
            <div className={css.couponTopContents}>
              {shptmDcTpCd === "CPN00401" && (
                <span className={css.couponLate}>{`${currSign}${dcAmt}`}</span>
              )}
              {shptmDcTpCd === "CPN00402" && (
                <span className={css.couponLate}>{`${cpnDctrt}%`}</span>
              )}
              <span className={css.title} aria-label={cpnTtl}>
                {cpnTtl}
              </span>
            </div>

            <div className={css.couponMiddleContents}>
              <span>
                {$L(
                  "Purchase over ${cpnAplyMinPurcAmt} (up to ${cpnAplyMaxDcAmt} off)"
                )
                  .replace("{cpnAplyMinPurcAmt}", cpnAplyMinPurcAmt)
                  .replace("{cpnAplyMaxDcAmt}", cpnAplyMaxDcAmt)}
              </span>
              <span className={classNames(css.content, css.date)}>
                {couponAplyStartDate}~{couponAplyEndDate}
              </span>
            </div>

            <div
              className={classNames(
                css.couponBottomButton,
                downloadCouponArr.length > 0 &&
                  downloadCouponArr.includes(cpnSno) &&
                  css.disable,
                downloadYn === "N" && css.disable,
                !downloadCouponArr.includes(cpnSno) &&
                  index === selectedCouponIndex &&
                  focused &&
                  css.focused
              )}
              aria-label="Download Button"
            >
              {downloadCouponArr.length > 0 &&
              downloadCouponArr.includes(cpnSno)
                ? $L("DOWNLOAD COMPLETED")
                : $L("DOWNLOAD")}
            </div>
          </div>
        </SpottableComponent>
      );
    },
    [selectedCoupon, downloadCouponArr, focused, dispatch]
  );

  return (
    <div className={css.detailContainer}>
      <ContainerLF>
        <TScroller
          verticalScrollbar={
            productOptionInfos && productOptionInfos.length > 2 && "auto"
          }
          className={classNames(
            css.detailScroll,
            productOptionInfos &&
              productOptionInfos.length > 1 &&
              css.optionSecondary,
            (!promotions || promotions.length === 0) && css.couponMissing
          )}
        >
          {productOptionInfos &&
            productOptionInfos.length > 0 &&
            productInfo.optProdYn === "Y" && (
              <ContainerLF spotlightId="billingProduct-optionContainer">
                {productOptionInfos.length !== 1 && (
                  <div className={css.optionLayer}>
                    {/* OPTION 1 */}
                    <span>
                      {$L(
                        productOptionInfos.length === 1 ? "OPTION" : "OPTION 1"
                      )}
                    </span>
                    <TButton
                      className={css.optionBtn}
                      onClick={
                        hasOnClose &&
                        handleOptionPopUpOpen(productOptionInfos, true)
                      }
                      spotlightId={"selectedOptionBox-0"}
                    >
                      <span className={css.optionValue}>
                        {renderOptionName()}
                      </span>
                    </TButton>
                  </div>
                )}

                <div className={css.optionLayer}>
                  {/* OPTION 2 */}
                  <span>
                    {$L(
                      productOptionInfos.length === 1 ? "OPTION" : "OPTION 2"
                    )}
                  </span>
                  <TButton
                    className={css.optionBtn}
                    onClick={
                      productOptionInfos[selectedBtnOptIdx]?.prdtOptDtl
                        .length !== 1 &&
                      handleOptionPopUpOpen(
                        productOptionInfos[selectedBtnOptIdx]?.prdtOptDtl,
                        false
                      )
                    }
                    spotlightId={"selectedOptionBox-1"}
                    spotlightDisabled={
                      productOptionInfos[selectedBtnOptIdx]?.prdtOptDtl
                        .length === 1
                    }
                  >
                    <span className={css.optionValue}>
                      {renderOptionValue()}
                    </span>
                  </TButton>
                </div>
              </ContainerLF>
            )}
          {/* QUANTITY */}
          <Container className={css.quantityLayer}>
            <span>{$L("QUANTITY")}</span>
            <div className={css.wrapper}>
              <TButton
                className={classNames(
                  css.quantityBtn,
                  css.decreaseBtn,
                  css.decreaseDimBtn
                )}
                // onClick={handlDecrement}
                spotlightDisabled
              />
              <span>{quantity}</span>
              <TButton
                className={classNames(
                  css.quantityBtn,
                  css.increaseBtn,
                  css.increaseDimBtn
                )}
                //  onClick={handleIncrement}
                spotlightDisabled
              />
            </div>
          </Container>
          <h3 className={css.messages}>
            Sorry, you can only order one at a time.
          </h3>
        </TScroller>
      </ContainerLF>
      <div className={css.temp}>
        <div className={css.middleLayer}>
          {/* COUPON */}
          <div className={css.couponWrap}>
            {promotions.map((promotion, idx) => {
              return (
                <Container
                  className={css.detailBottomLayer}
                  key={`coupon: ${idx}`}
                >
                  <div className={css.leftLayer}>
                    <span className={css.promotionName}>{promotion}</span>
                    <span className={css.promotionDesc}>{promotionDesc}</span>
                  </div>
                  <TButton
                    className={css.promotionBtn}
                    onSpotlightLeft={onSpotlightLeftCoupon}
                    onClick={() => {
                      handleCouponClick(idx, promotion);
                    }}
                  >
                    {$L("COUPON")}
                  </TButton>
                </Container>
              );
            })}
          </div>

          {/* Price */}
          <BillingProductPrice
            productInfo={productInfo}
            selectedOptions={selectedOptions}
            patncNm={patncNm || productData?.patncNm}
          />
        </div>
        {/* BYU NOW & FAVORITE */}
        <div>
          <Container className={css.bottomBtnLayer}>
            <TButton
              className={css.buyNowBtn}
              onClick={handleClickBuyNow}
              spotlightId={SpotlightIds.DETAIL_BUYNOW}
              spotlightDisabled={productInfo.soldoutFlag === "Y"}
            >
              {$L("BUY NOW")}
            </TButton>
            <FavoriteBtn
              selectedPatnrId={selectedPatnrId}
              selectedPrdtId={selectedPrdtId}
              favoriteFlag={favoriteFlag}
              onFavoriteFlagChanged={onFavoriteFlagChanged}
              logMenu={logMenu}
            />
          </Container>
          <div className={css.disclaimerContainer}>
            {productInfo.disclaimer}
          </div>
        </div>
      </div>
      {/* LOGIN POPUP */}
      {activePopup === Config.ACTIVE_POPUP.loginPopup && (
        <TPopUp
          kind="textPopup"
          hasText
          open={popupVisible}
          text={loginPopupText}
          hasButton
          hasOnClose={hasOnClose}
          button1Text={$L("OK")}
          button2Text={$L("CANCEL")}
          onClick={handleLoginPopUpOpen}
          onClose={onClose}
        ></TPopUp>
      )}
      {/* SHOPTIME OPTION POPUP */}
      {activePopup === Config.ACTIVE_POPUP.optionPopup && (
        <TPopUp
          kind="optionPopup"
          options={selectedOptionInfo}
          onClose={() => onClose("billingProduct-optionContainer")}
          open={popupVisible}
          optionClick={
            hasProductOptionArray ? handleOptionClick : handleOptionItemClick
          }
          hasButton
          hasText
          title={$L("OPTIONS TOTAL")}
          button1Text={$L("CLOSE")}
          className={css.productOptionPopup}
          selectedIndex={
            hasProductOptionArray ? selectedBtnOptIdx : selectedOptionItemIndex
          }
        />
      )}
      {/* COUPON POPUP */}
      {activePopup === Config.ACTIVE_POPUP.couponPopup && (
        <TPopUp
          kind="couponPopup"
          hasText
          title={couponTypes === 0 ? promotions[0] : promotions[1]}
          open={popupVisible}
          onClick={handleCouponTotDownload}
          onClose={onClose}
          hasButton
          button1Text={$L("DOWNLOAD ALL")}
          button2Text={$L("CLOSE")}
        >
          <Container className={css.itemWrap}>
            {selectedCoupon && selectedCoupon.length > 0 && (
              <TVirtualGridList
                dataSize={selectedCoupon.length}
                direction="horizontal"
                autoScroll
                renderItem={renderItem}
                itemWidth={440}
                itemHeight={320}
                spacing={15}
                className={css.itemList}
              />
            )}
          </Container>
          <div
            className={css.couponRemain}
          >{`1/${selectedCoupon?.length}`}</div>
        </TPopUp>
      )}
      {activePopup === Config.ACTIVE_POPUP.qrPopup && (
        <TPopUp kind="qrPopup" open={popupVisible} onClose={onClose}>
          <div className={css.popupContainer}>
            <div className={css.header}>
              <h3>{$L("QR CODE")}</h3>
            </div>

            <div className={css.qrcodeContainer}>
              <div className={css.qrcode}>
                <TQRCode
                  text={detailBuyNowUrl}
                  isBillingProductVisible
                  width="360"
                  height="360"
                />
              </div>

              <h3>
                {$L(
                  "If you want to add or edit your address and payment information, please scan the QR CODE."
                )}
              </h3>
              <TButton className={css.popupBtn} onClick={onClose}>
                {$L("CLOSE")}
              </TButton>
            </div>
          </div>
        </TPopUp>
      )}
    </div>
  );
}
