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

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

import Spotlight from "@enact/spotlight";
import Marquee from "@enact/ui/Marquee";

import { setShowPopup } from "../../../actions/commonActions";
import TButton from "../../../components/TButton/TButton";
import TQRCode from "../../../components/TQRCode/TQRCode";
import usePriceInfo from "../../../hooks/usePriceInfo";
import useWhyDidYouUpdate from "../../../hooks/useWhyDidYouUpdate";
import * as Config from "../../../utils/Config";
import { $L } from "../../../utils/helperMethods";
import FavoriteBtn from "../components/FavoriteBtn";
import css from "./UnableOption.module.less";

export default function UnableOption({
  handleMobileSendPopupOpen,
  patnrName,
  productInfo,
  selectedPatnrId,
  selectedPrdtId,
  soldoutFlag,
  logMenu,
}) {
  const dispatch = useDispatch();
  const { USE_STATE, USE_SELECTOR } = useWhyDidYouUpdate("UnableOption", {
    handleMobileSendPopupOpen,
    patnrName,
    productInfo,
    selectedPatnrId,
    selectedPrdtId,
    soldoutFlag,
  });

  const isLoading = USE_SELECTOR(
    "isLoading",
    (state) => state.common.appStatus?.showLoadingPanel?.show
  );
  const [favoriteFlag, setFavoriteFlag] = USE_STATE(
    "favoriteFlag",
    productInfo?.favorYn
  );
  const [isShowQRCode, setIsShowQRCode] = USE_STATE("isShowQRCode", true);
  const timerRef = useRef(null);

  const tooltipDes = $L("Scan for more information about the product.");
  const promotionTooltip = (
    <>
      Scan for more information about the product.
      <br />
      and
      <br />
      enter the promo code
    </>
  );

  const { price5, priceInfo, rewd, offerInfo, patncNm, installmentMonths } =
    productInfo;

  const {
    discountRate,
    // rewardFlag,
    discountedPrice,
    discountAmount,
    originalPrice,
    promotionCode,
  } = usePriceInfo(priceInfo) || {};

  const popupVisible = USE_SELECTOR(
    "popupVisible",
    (state) => state.common.popup?.popupVisible
  );
  const isOriginalPriceEmpty = useMemo(() => {
    return parseFloat(originalPrice.replace(/[^0-9.-]+/g, "")) === 0;
  }, [originalPrice]);

  const isDiscountedPriceEmpty = useMemo(() => {
    return parseFloat(discountedPrice.replace(/[^0-9.-]+/g, "")) === 0;
  }, [discountedPrice]);

  const TYPE_CASE = useMemo(
    () => ({
      case1: !isOriginalPriceEmpty && isDiscountedPriceEmpty && !price5,
      case2: !isOriginalPriceEmpty && !isDiscountedPriceEmpty && !price5,
      case3: !isOriginalPriceEmpty && !isDiscountedPriceEmpty && price5,
      case4: !isOriginalPriceEmpty && isDiscountedPriceEmpty && price5,
      case5: !isOriginalPriceEmpty && isDiscountedPriceEmpty && !price5,
      case6: !isOriginalPriceEmpty && !isDiscountedPriceEmpty && !price5,
      case7: !isOriginalPriceEmpty && !isDiscountedPriceEmpty && price5,
      case8: !isOriginalPriceEmpty && isDiscountedPriceEmpty && price5,
      case9: !!(isOriginalPriceEmpty && isDiscountedPriceEmpty && offerInfo),
    }),
    [isOriginalPriceEmpty, isDiscountedPriceEmpty, price5, offerInfo]
  );
  useEffect(() => {
    const current = Spotlight.getCurrent();
    let hasProperSpot = false;
    if (current) {
      const spotId = current.getAttribute("data-spotlight-id");
      if (spotId) {
        if (
          spotId.indexOf("indicator-image") >= 0 ||
          spotId.indexOf("indicator-shopbymobile_Btn") >= 0
        ) {
          hasProperSpot = true;
        }
      }
    }
    let spotFocus = null;
    if (!hasProperSpot) {
      if (soldoutFlag) {
        spotFocus = setTimeout(() => {
          Spotlight.focus("spotlightId_backBtn");
        }, 0);
      } else if (!popupVisible) {
        spotFocus = setTimeout(() => {
          Spotlight.focus("shopbymobile_Btn");
        }, 0);
      }
    }
    return () => {
      clearTimeout(spotFocus);
    };
  }, [soldoutFlag, productInfo, isLoading]);

  const targetReward = useMemo(() => {
    if (productInfo && rewd) {
      const rewards = rewd.split("|");
      const targetReward = rewards[3].trim();

      return targetReward;
    } else if (price5) {
      return price5;
    }

    return null;
  }, [productInfo, rewd, price5]);

  const handleSMSClick = useCallback(() => {
    dispatch(setShowPopup(Config.ACTIVE_POPUP.smsPopup));

    if (handleMobileSendPopupOpen) {
      handleMobileSendPopupOpen();
    }
  }, [dispatch, handleMobileSendPopupOpen]);

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

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

  const isDiscounted = useMemo(() => {
    return discountedPrice !== originalPrice;
  }, [discountedPrice, originalPrice]);

  const renderPriceItem = useCallback(() => {
    if (productInfo && !promotionCode) {
      if (rewd) {
        return (
          <div className={css.wrapper}>
            <div className={css.rewdTopLayer}>
              <span>
                {patncNm
                  ? patncNm + " " + $L("Price") + " "
                  : patnrName + " " + $L("Price") + " "}
              </span>
              <span className={css.partnerPrc}>
                {TYPE_CASE.case5 || TYPE_CASE.case8
                  ? isOriginalPriceEmpty
                    ? offerInfo
                    : originalPrice
                  : discountedPrice}
              </span>
            </div>
            <div className={css.rewdBtmLayer}>
              <span className={css.rewdNm}>{$L("Shop Time Price")}</span>
              <div className={css.btmPrc}>
                {/* TODO : rewd data*/}
                {/* 분할금액 조건문처리 케이스별로  */}

                <span className={css.rewdRate}>{discountedPrice} </span>
                {/* 리워드 금액 */}
                {(TYPE_CASE.case7 ||
                  TYPE_CASE.case5 ||
                  TYPE_CASE.case6 ||
                  TYPE_CASE.case8) && (
                  <span className={css.rewdPrc}>
                    {$L("Save") + discountAmount + discountRate}
                  </span>
                )}
              </div>
            </div>
          </div>
        );
      } else {
        if (TYPE_CASE.case1 || TYPE_CASE.case4) {
          return (
            <div className={css.wrapper}>
              <span className={css.name}>
                {patncNm
                  ? patncNm + " " + $L("Price")
                  : patnrName + " " + $L("Price")}
              </span>
              <div className={css.btmLayer}>
                <span className={classNames(css.price, css.case01)}>
                  {isOriginalPriceEmpty ? offerInfo : originalPrice}
                </span>
              </div>
            </div>
          );
        } else if (TYPE_CASE.case2) {
          if (
            selectedPrdtId === "27LX6TYGA" &&
            offerInfo &&
            offerInfo?.length > 0
          ) {
            return (
              <div className={css.wrapper}>
                <span
                  dangerouslySetInnerHTML={{
                    __html: offerInfo && offerInfo,
                  }}
                />
              </div>
            );
          }
          return (
            <div className={css.wrapper}>
              <div className={css.topLayer}>
                {discountRate && Number(discountRate.replace("%", "")) > 4 && (
                  <div className={css.rateTag}>{discountRate}</div>
                )}
                <span className={css.name}>
                  {patncNm
                    ? patncNm + " " + $L("Price")
                    : patnrName + $L("Price")}
                </span>
              </div>
              <div className={css.btmLayer}>
                <span className={css.price}>
                  {isDiscountedPriceEmpty ? offerInfo : discountedPrice}
                </span>
                {isDiscounted && (
                  <span className={css.discountedPrc}>
                    {originalPrice && isOriginalPriceEmpty
                      ? offerInfo
                      : originalPrice}
                  </span>
                )}
              </div>
            </div>
          );
        } else if (TYPE_CASE.case3) {
          return (
            <div className={css.wrapper}>
              <span className={css.name}>
                {patncNm
                  ? patncNm + " " + $L("Price")
                  : patnrName + " " + $L("Price")}
              </span>
              <div className={css.btmLayer}>
                {discountRate && Number(discountRate.replace("%", "")) > 4 && (
                  <div className={css.rateTag}>{discountRate}</div>
                )}
                <span className={css.price}>
                  {isDiscountedPriceEmpty ? offerInfo : discountedPrice}
                </span>
                {isDiscounted && (
                  <span className={css.discountedPrc}>
                    {originalPrice && isOriginalPriceEmpty
                      ? offerInfo
                      : originalPrice}
                  </span>
                )}
              </div>
              {/* 할부 */}
            </div>
          );
        }
      }
    } else if (promotionCode) {
      return (
        <div className={css.wrapper}>
          <div className={css.topLayer}>
            {discountRate && Number(discountRate.replace("%", "")) > 4 && (
              <div className={css.rateTag}>{discountRate}</div>
            )}
            <span className={css.name}>{$L("Shop Time Price")}</span>
          </div>
          <div className={css.btmLayer}>
            <span className={css.price}>{discountedPrice}</span>
            {discountedPrice !== originalPrice && (
              <span className={css.discountedPrc}>
                {originalPrice && isOriginalPriceEmpty
                  ? offerInfo
                  : originalPrice}
              </span>
            )}
          </div>
        </div>
      );
    }
    if (TYPE_CASE.case9) {
      if (
        selectedPrdtId === "27LX6TYGA" &&
        offerInfo &&
        offerInfo?.length > 0
      ) {
        return (
          <div className={css.wrapper}>
            <span
              dangerouslySetInnerHTML={{
                __html: offerInfo && offerInfo,
              }}
            />
          </div>
        );
      }
      return (
        <div className={css.wrapper}>
          <span className={css.partnerName}>
            {patncNm ? patncNm + " " + $L("Price") : patnrName + $L("Price")}
          </span>
          <span className={css.offerInfo}>{offerInfo}</span>
        </div>
      );
    }
  }, [
    patnrName,
    productInfo,
    isOriginalPriceEmpty,
    isDiscountedPriceEmpty,
    TYPE_CASE,
    offerInfo,
  ]);

  useEffect(() => {
    const toggleQRCode = () => {
      if (isShowQRCode) {
        timerRef.current = setTimeout(() => {
          setIsShowQRCode(false);
        }, 10000);
      } else {
        timerRef.current = setTimeout(() => {
          setIsShowQRCode(true);
        }, 5000);
      }
    };

    toggleQRCode();

    return () => {
      if (timerRef.current) {
        clearTimeout(timerRef.current);
      }
    };
  }, [isShowQRCode]);

  return (
    <div className={css.priceContainer}>
      <div>
        <div className={css.priceDetail}>
          {productInfo && renderPriceItem()}
          {/* QR */}
          {
            <div className={css.qrWrapper}>
              {productInfo?.qrImgUrl
                ? productInfo?.qrImgUrl
                : productInfo?.qrcodeUrl &&
                  (isShowQRCode ? (
                    <>
                      <TQRCode
                        text={productInfo?.qrcodeUrl}
                        width="252"
                        height="252"
                      />
                      <div className={css.tooltip}>
                        <div className={css.tooltipBody}>
                          {promotionCode ? promotionTooltip : tooltipDes}
                        </div>
                      </div>
                    </>
                  ) : (
                    <div className={css.qrRollingWrap}>
                      <div className={css.innerText}>
                        <h3>{$L("Scan QR")}</h3>
                        <p>{$L("with your phone, Check Product")}</p>
                        <p>{$L("info & Purchase easily")}</p>
                      </div>
                    </div>
                  ))}
            </div>
          }
        </div>
        {!TYPE_CASE.case9 && targetReward && installmentMonths && (
          <div className={css.installedPrc}>
            <h3 className={css.text}>
              {$L("OR {price} with {months}-month financing")
                .replace("{price}", targetReward)
                .replace("{months}", installmentMonths)}
            </h3>
          </div>
        )}
        {promotionCode && (
          <div className={css.promotionContainer}>
            <div className={css.promotionContents}>
              <div>{$L("Promo Code")}</div>
              <h3>{promotionCode}</h3>
            </div>
          </div>
        )}
      </div>
      <div className={css.bottomContainer}>
        <div className={css.btnContainer}>
          <TButton
            className={css.smsBtn}
            onClick={handleSMSClick}
            spotlightId="shopbymobile_Btn"
          >
            {$L("SHOP BY MOBILE")}
          </TButton>
          <FavoriteBtn
            selectedPatnrId={selectedPatnrId}
            selectedPrdtId={selectedPrdtId}
            favoriteFlag={favoriteFlag}
            onFavoriteFlagChanged={onFavoriteFlagChanged}
            logMenu={logMenu}
          />
        </div>
        <Marquee marqueeOn="render" className={css.disclaimerContainer}>
          {productInfo?.disclaimer}
        </Marquee>
      </div>
    </div>
  );
}
