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

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

import Spotlight from "@enact/spotlight";
import Spottable from "@enact/spotlight/Spottable";

import defaultLogoImg from "../../../../../assets/images/ic-tab-partners-default@3x.png";
import defaultImage from "../../../../../assets/images/img-thumb-empty-144@3x.png";
import { setHidePopup, setShowPopup } from "../../../../actions/commonActions";
import CustomImage from "../../../../components/CustomImage/CustomImage";
import TButtonScroller from "../../../../components/TButtonScroller/TButtonScroller";
import TButtonTab from "../../../../components/TButtonTab/TButtonTab";
import TPopUp from "../../../../components/TPopUp/TPopUp";
import TQRCode from "../../../../components/TQRCode/TQRCode";
import * as Config from "../../../../utils/Config";
import {
  $L,
  getQRCodeUrl,
  removeSpecificTags,
  scaleH,
  scaleW,
} from "../../../../utils/helperMethods";
import ProductTag from "../../components/ProductTag";
import StarRating from "../../components/StarRating";
import css from "./IndicatorOptions.module.less";

const SpottableComponent = Spottable("div");
const tooltipDes = $L(
  "Please check for more detailed infomation about the product"
);
export default function IndicatorOptions({
  address,
  handleIndicatorOptions,
  handleMobileSendPopupOpen,
  isBillingProductVisible,
  isCall,
  isDescription,
  isFullOption,
  productInfo,
  thumbnailUrl,
  detailQRCodeUrl,
  nowMenu,
}) {
  const [tabLabel, setTabLabel] = useState("");
  const [description, setDescription] = useState("");
  const { popupVisible, activePopup } = useSelector(
    (state) => state.common.popup
  );

  const dispatch = useDispatch();

  const handleSMSonClose = useCallback(
    (e) => {
      const spotlightId =
        tabLabel[0] === $L("DESCRIPTION")
          ? "description_Btn"
          : "return_Exchanges_Btn";

      dispatch(setHidePopup());

      setTimeout(() => {
        Spotlight.focus(spotlightId);
      });
    },
    [dispatch, tabLabel]
  );

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

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

  const descriptionClick = useCallback(
    (label, description) => {
      setTabLabel([label]);
      setDescription(description);
      dispatch(setShowPopup(Config.ACTIVE_POPUP.descriptionPopup));

      if (handleIndicatorOptions) {
        handleIndicatorOptions();
      }
    },
    [dispatch, handleIndicatorOptions]
  );
  const productDescription = () => {
    const sanitizedString = removeSpecificTags(description);
    return { __html: sanitizedString };
  };

  const qrCodeUrl = useMemo(() => {
    if (!isBillingProductVisible) return productInfo?.qrcodeUrl;

    return detailQRCodeUrl;
  }, [productInfo, isBillingProductVisible, detailQRCodeUrl]);

  //DecoratorContainer로 컴포넌트를 감싸주면 해당 함수가 필요없어 보임
  const onSpotlightLeft = (e) => {
    e.stopPropagation();
    Spotlight.focus("");
  };

  const onSpotlightRight = () => {
    Spotlight.focus("spotlightId_TbuttonScrollerDown");
  };

  const renderPopUp = () => {
    return (
      <TPopUp
        kind="descriptionPopup"
        onClose={handleSMSonClose}
        open={popupVisible}
        hasButton
        button1Text={$L("CLOSE")}
        spotlightId="tPopupBtn1"
        onSpotlightRight={onSpotlightRight}
      >
        <div>
          <div className={css.popUpHeader}>
            <p>
              <CustomImage
                src={thumbnailUrl}
                fallbackSrc={defaultImage}
                ariaLabel={productInfo?.prdtNm}
                alt=""
              />
            </p>
            <div className={css.path}>
              <div>
                <CustomImage
                  src={productInfo?.patncLogoPath}
                  fallbackSrc={defaultLogoImg}
                  ariaLabel={
                    productInfo?.patncNm + ", ID : " + productInfo?.prdtId
                  }
                  alt=""
                />
                {productInfo?.expsPrdtNo && (
                  <span>{$L("ID") + " : " + productInfo?.expsPrdtNo}</span>
                )}
              </div>
              <h3>{productInfo?.prdtNm}</h3>
              <div className={css.tagWrap}>
                {productInfo?.revwGrd && (
                  <StarRating
                    rating={productInfo?.revwGrd}
                    className={css.starRating}
                  />
                )}
                <ProductTag productInfo={productInfo} />
              </div>
            </div>
          </div>
          <div className={css.line} />
          <div className={css.tButtonTab}>
            <TButtonTab
              selectedIndex={0}
              contents={tabLabel}
              className={css.tab}
              spotlightDisabled={true}
            />
            <TButtonScroller
              boxHeight={scaleH(300)}
              width={scaleW(980)}
              className={css.popupDescription}
            >
              <div dangerouslySetInnerHTML={productDescription()} />
            </TButtonScroller>
          </div>
        </div>
      </TPopUp>
    );
  };
  //
  return (
    <>
      <div className={css.indicatorOptionContainer}>
        {activePopup === Config.ACTIVE_POPUP.descriptionPopup && renderPopUp()}
        {address && (
          <div className={css.address}>
            <span className={css.location} />
            <div>{address}</div>
          </div>
        )}

        {(isCall || isFullOption) &&
          productInfo?.orderPhnNo &&
          productInfo?.orderPhnProdFlag === "Y" && (
            <div className={css.order} aria-label={productInfo?.orderPhnNo}>
              <div className={css.icon}>
                <span />
                <div>{productInfo?.orderPhnNo}</div>
              </div>
            </div>
          )}
        {isDescription && (
          <div
            className={css.description}
            spotlightId="spotlightId-indicatorOptions"
          >
            <SpottableComponent
              onClick={() =>
                productInfo?.prdtDesc &&
                descriptionClick($L("DESCRIPTION"), productInfo?.prdtDesc)
              }
              className={!productInfo?.prdtDesc && css.buttonDisable}
              spotlightDisabled={!productInfo?.prdtDesc}
              spotlightId="description_Btn"
              onSpotlightLeft={onSpotlightLeft}
            >
              {$L("DESCRIPTION")}
            </SpottableComponent>
          </div>
        )}
        {isFullOption && (
          <div spotlightId="spotlightId-indicatorOptions">
            <div className={css.buttonWrap}>
              <div className={css.tButton}>
                <SpottableComponent
                  onClick={() =>
                    productInfo?.prdtDesc &&
                    descriptionClick($L("DESCRIPTION"), productInfo?.prdtDesc)
                  }
                  className={!productInfo?.prdtDesc && css.buttonDisable}
                  spotlightDisabled={!productInfo?.prdtDesc}
                  spotlightId="description_Btn"
                  onSpotlightLeft={onSpotlightLeft}
                >
                  {$L("DESCRIPTION")}
                </SpottableComponent>
                <SpottableComponent
                  onClick={() =>
                    productInfo?.prodRtunIntchDescCtntc &&
                    descriptionClick(
                      $L("RETURNS & EXCHANGES"),
                      productInfo?.prodRtunIntchDescCtntc
                    )
                  }
                  className={
                    !productInfo?.prodRtunIntchDescCtntc && css.buttonDisable
                  }
                  spotlightDisabled={!productInfo?.prodRtunIntchDescCtntc}
                  spotlightId="return_Exchanges_Btn"
                  onSpotlightLeft={onSpotlightLeft}
                >
                  {$L("RETURNS & EXCHANGES")}
                </SpottableComponent>
                <SpottableComponent
                  onClick={handleSMSClick}
                  spotlightId="shopbymobile_Btn"
                  onSpotlightLeft={onSpotlightLeft}
                >
                  {$L("SHOP BY MOBILE")}
                </SpottableComponent>
              </div>

              <div className={css.qrcode}>
                {productInfo?.qrImgUrl ? (
                  productInfo?.qrImgUrl
                ) : (
                  <TQRCode
                    text={qrCodeUrl}
                    isBillingProductVisible={isBillingProductVisible}
                    width="160"
                    height="160"
                  />
                )}
                <div className={css.tooltip}>
                  <div className={css.tooltipBody}>{tooltipDes}</div>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </>
  );
}
