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

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

import { Job } from "@enact/core/util";
import Spotlight from "@enact/spotlight";
import SpotlightContainerDecorator from "@enact/spotlight/SpotlightContainerDecorator";
import Spottable from "@enact/spotlight/Spottable";
import { setContainerLastFocusedElement } from "@enact/spotlight/src/container";

import defaultLogoImg from "../../../../../assets/images/ic-tab-partners-default@3x.png";
// getMyinfoOrderCancelSearch : 회원 주문 취소/반품/교환 조회 - 디테일
// paymentTotalCancel : 주문 부분 결제 취소
// updateOrderPartialCancel : 결제전체취소
import {
  getMyinfoOrderCancelSearch,
  paymentTotalCancel,
  updateOrderPartialCancel,
} from "../../../../actions/cancelActions";
import {
  setHidePopup,
  setHideSecondaryPopup,
  setShowPopup,
  setShowSecondaryPopup,
} from "../../../../actions/commonActions";
import {
  sendLogOrderBtnClick,
  sendLogOrderChange,
  sendLogTotalRecommend,
} from "../../../../actions/logActions";
// getMyinfoOrderSearch : 회원 주문 정보 조회
// getMyinfoOrderDetailSearch : 회원 주문 상세 정보 조회 - 디테일
// getMyinfoOrderShippingSearch : 회원 주문 배송 상세 정보 조회
import {
  clearMyinfoOrderSearch,
  continueGetMyinfoOrderSearch,
  getMyinfoOrderDetailSearch,
  getMyinfoOrderSearch,
  getMyinfoOrderShippingSearch,
} from "../../../../actions/orderActions";
import { updatePanel } from "../../../../actions/panelActions";
import CustomImage from "../../../../components/CustomImage/CustomImage";
import TBody from "../../../../components/TBody/TBody";
import TButton, { TYPES } from "../../../../components/TButton/TButton";
import TButtonTab, {
  LIST_TYPE,
} from "../../../../components/TButtonTab/TButtonTab";
import TDropDown from "../../../../components/TDropDown/TDropDown";
import THeader from "../../../../components/THeader/THeader";
import TPopUp from "../../../../components/TPopUp/TPopUp";
import TQRCode from "../../../../components/TQRCode/TQRCode";
import TScroller from "../../../../components/TScroller/TScroller";
import TVerticalPagenator from "../../../../components/TVerticalPagenator/TVerticalPagenator";
import usePrevious from "../../../../hooks/usePrevious";
import * as Config from "../../../../utils/Config";
import { GET_MY_INFO_ORDER_SEARCH_LIMIT } from "../../../../utils/Config";
import {
  $L,
  formatCurrencyValue,
  getFormattingDate,
  isElementInContainer,
} from "../../../../utils/helperMethods";
import { SpotlightIds } from "../../../../utils/SpotlightIds";
import NoOrderList from "./components/NoOrderList";
import OrderListCard from "./components/OrderListCard";
import css from "./MyOrders.module.less";

const Container = SpotlightContainerDecorator("div");
const ListContainer = SpotlightContainerDecorator("div");
const TabContainer = SpotlightContainerDecorator(
  { enterTo: "last-focused" },
  "div"
);
const CancelReasonListContainer = SpotlightContainerDecorator(
  { enterTo: "last-focused" },
  "div"
);

const SpottableListItem = Spottable("div");

const getButtonTabList = () => {
  return [$L("ORDERS"), $L("CANCELLED ORDERS")];
};

export default function MyOrders({ title, panelInfo, isOnTop }) {
  const buttonTabList = useMemo(() => getButtonTabList(), []);
  const dispatch = useDispatch();

  const dataAppendJob = useRef(new Job((func) => func(), 1000));

  const userNumber = useSelector(
    (state) => state.common.appStatus?.loginUserData?.userNumber
  );
  const orderDetailData =
    useSelector((state) => state.order?.orderDetailData?.orderInfo?.[0]) || {};
  const orderInfoData = useSelector((state) => state.order?.orderInfoData);
  const cancelOrderInfoData = useSelector(
    (state) => state.order?.cancelOrderInfoData
  );
  const isLoading = useSelector(
    (state) => state.common.appStatus?.showLoadingPanel?.show
  );
  const orderSearchParams = useSelector(
    (state) => state.order?.orderSearchParams
  );
  const popup = useSelector((state) => state.common.popup);
  const cancelReasonInfo = useSelector(
    (state) => state.cancel.cancelReasonInfoData?.cancelCodeInfo
  );
  const { dlvrHistDetailInfo, dlvrHistInfo } = useSelector(
    (state) => state.order.orderShippingData
  );

  const { popupVisible, activePopup, data } = popup || {};

  const orderInfo = orderInfoData?.orderInfo || {};
  const cancelOrderInfo = cancelOrderInfoData?.orderInfo || {};
  const {
    currSign,
    currSignLoc,
    totProdPrc,
    totDcAmt,
    totDlvrAmt,
    ordPmtReqAmt,
    ordPmtNoTaxAmt,
    ordTotTaxAmt,
  } = orderDetailData || {};

  const cbChangePageRef = useRef(null);
  const focusedContainerIdRef = useRef(null);

  const [selectedTab, setSelectedTab] = useState(
    panelInfo.selectedTab ? panelInfo.selectedTab : 0
  );
  const [dropDownTab, setDropDownTab] = useState(
    panelInfo.dropDownTab ? panelInfo.dropDownTab : 0
  );
  const [styleChange, setStyleChange] = useState(false);
  const [selectedCancelItem, setSelectedCancelItem] = useState(null);
  const [cancelReason, setCancelReason] = useState("");
  const listContainerRef = useRef(null);
  const tabRef = usePrevious(selectedTab);
  const dropDownTabRef = usePrevious(dropDownTab);
  const orderInfoDataRef = usePrevious(orderInfoData);
  const cancelOrderInfoDataRef = usePrevious(cancelOrderInfoData);

  const filterMethods = useMemo(
    () => [
      $L("Last 1 Month"),
      $L("Last 3 Month"),
      $L("Last 6 Month"),
      $L("Last 12 Month"),
    ],
    []
  );

  const reload = useCallback(
    (forceUpdate = false) => {
      const cancelOrderYn = tabRef.current === 0 ? "N" : "Y";

      let srchMonth;
      switch (dropDownTabRef.current) {
        case 0: // Last 1 Month
          srchMonth = 1;
          break;
        case 1: // Last 3 Month
          srchMonth = 3;
          break;
        case 2: // Last 6 Month
          srchMonth = 6;
          break;
        case 3: // Last 12 Month
          srchMonth = 12;
          break;
        default:
          srchMonth = 3; // 기본값
      }

      if (
        forceUpdate ||
        orderSearchParams.srchMonth !== srchMonth ||
        orderSearchParams.cancelOrderYn !== cancelOrderYn
      ) {
        dispatch(
          getMyinfoOrderSearch({
            mbrNo: userNumber,
            srchMonth: srchMonth,
            cancelOrderYn: cancelOrderYn,
          })
        );
      }
    },
    [userNumber, orderSearchParams, selectedTab, dropDownTab]
  );

  useEffect(() => {
    if (!panelInfo.skipReload) {
      reload(true);
    } else {
      dispatch(updatePanel({ skipReload: false }));
    }
  }, []);

  useEffect(() => {
    if (isOnTop) {
      if (panelInfo.dropDownTab !== dropDownTab) {
        setDropDownTab(panelInfo.dropDownTab ? panelInfo.dropDownTab : 0);
      }

      if (panelInfo.selectedTab !== selectedTab) {
        setContainerLastFocusedElement(null, [
          SpotlightIds.MY_PAGE_MY_ORDER_BOX,
        ]);

        setSelectedTab(panelInfo.selectedTab ? panelInfo.selectedTab : 0);
        Spotlight.focus("tab-" + panelInfo.selectedTab);
      } else if (panelInfo.currentSpot) {
        Spotlight.focus(panelInfo.currentSpot);
      }

      setTimeout(() => {
        Spotlight.focus(SpotlightIds.TBODY);

        if (panelInfo.currentSpot) {
          Spotlight.focus(panelInfo.currentSpot);
        }

        reload();
      }, 100);
    }
  }, [isOnTop, panelInfo]);

  useEffect(() => {
    if (orderInfoData || cancelOrderInfoData) {
      const tabNode = document.querySelector(
        `[data-spotlight-id="${"tab-" + selectedTab}"]`
      );

      if (tabNode) {
        setContainerLastFocusedElement(tabNode, [
          SpotlightIds.MY_PAGE_MY_ORDER_TAB_CONTAINER,
        ]);
      }
    }
  }, [orderInfoData, cancelOrderInfoData, selectedTab]);

  useEffect(() => {
    setContainerLastFocusedElement(null, [SpotlightIds.MY_PAGE_MY_ORDER_BOX]);
    reload();
  }, [selectedTab, dropDownTab]);

  useEffect(() => {
    const c = document.getElementById("floatLayer");

    c.classList.add("myOrders_dropdown");
    return () => {
      c.classList.remove("myOrders_dropdown");
    };
  }, []);

  const sendLogButtonClick = useCallback(
    (buttonName, tabName) => {
      const params = {
        contextName: Config.LOG_CONTEXT_NAME.MYORDER,
        messageId: Config.LOG_MESSAGE_ID.BUTTONCLICK,
        tabTitle: tabName ? tabName : buttonTabList[selectedTab],
        buttonTitle: buttonName,
      };

      dispatch(sendLogTotalRecommend(params));
    },
    [dispatch, buttonTabList, selectedTab]
  );
  const handleButtonTabClick = useCallback(
    ({ index, ...rest }) => {
      if (index === selectedTab) {
        return;
      }

      setSelectedTab(index);

      if (cbChangePageRef.current) {
        cbChangePageRef.current(0, false, false);
      }

      sendLogButtonClick(buttonTabList[index], buttonTabList[index]);
    },
    [selectedTab]
  );

  const handleSelectFilter = useCallback(
    ({ selected }) => {
      if (selected === dropDownTab) {
        return;
      }
      setDropDownTab(selected);
    },
    [dropDownTab]
  );

  const handleStyle = useCallback(() => {
    setStyleChange(true);
  }, []);

  const handleStyleOut = useCallback(() => {
    setStyleChange(false);
  }, []);

  const showGotoTopButton = useMemo(() => {
    const targetData = selectedTab === 0 ? orderInfoData : cancelOrderInfoData;

    if (!targetData && !targetData.orderInfo) {
      if (!targetData.orderInfo.length === 0) {
        return false;
      }
    }

    if (targetData && targetData.orderInfo && targetData.orderInfoCount) {
      return targetData.orderInfo.length >= targetData.orderInfoCount;
    }

    return false;
  }, [orderInfoData, cancelOrderInfoData, selectedTab]);

  const handleTopButtonClick = useCallback(() => {
    if (cbChangePageRef.current) {
      cbChangePageRef.current(0, true, false);
    }

    setContainerLastFocusedElement(null, [SpotlightIds.MY_PAGE_MY_ORDER_BOX]);
    Spotlight.focus("tab-" + selectedTab);

    sendLogButtonClick("TOP");
  }, [selectedTab]);

  const onScrollStop = useCallback((event) => {
    const childrenItems = document.querySelector(
      `[data-spotlight-id="${SpotlightIds.MY_PAGE_MY_ORDER_BOX}"]`
    ).childNodes;
    const targetData =
      tabRef.current === 0
        ? orderInfoDataRef.current
        : cancelOrderInfoDataRef.current;

    let visibleIndexes = [];

    childrenItems.forEach((child, index) => {
      if (isElementInContainer(child, null, false)) {
        visibleIndexes.push(index);
      }
    });

    if (visibleIndexes.length > 0) {
      const lastVisibleIndex = visibleIndexes[visibleIndexes.length - 1];

      if (lastVisibleIndex === childrenItems.length - 1) {
        const nextQueryIndex =
          Math.floor(lastVisibleIndex / GET_MY_INFO_ORDER_SEARCH_LIMIT + 1) *
          GET_MY_INFO_ORDER_SEARCH_LIMIT;

        if (
          targetData &&
          targetData.orderInfo &&
          !targetData.orderInfo[nextQueryIndex]
        ) {
          dataAppendJob.current.throttle(() => {
            dispatch(
              continueGetMyinfoOrderSearch(
                Math.floor(nextQueryIndex / GET_MY_INFO_ORDER_SEARCH_LIMIT) + 1
              )
            );
          });
        }
      }
    }
  }, []);

  const handleClosePopupBtn = useCallback(() => {
    dispatch(setHidePopup());

    sendLogButtonClick("POPUP CLOSE");
  }, [dispatch, buttonTabList, selectedTab]);

  const onClickBuyAgain = useCallback(
    (ev) => {
      const target = ev.currentTarget;
      let currentSpotId = null;

      if (target) {
        currentSpotId = target.getAttribute("data-spotlight-id");

        dispatch(
          updatePanel({
            name: Config.panel_names.MY_PAGE_PANEL,
            panelInfo: {
              currentSpot: currentSpotId,
              selectedTab: tabRef.current,
              dropDownTab: dropDownTabRef.current,
              focusedContainerId: focusedContainerIdRef.current,
              skipReload: true,
            },
          })
        );
      }
    },
    [dispatch]
  );

  const onFocusedContainerId = useCallback((containerId) => {
    focusedContainerIdRef.current = containerId;
  }, []);

  const handleStopScrollBar = useCallback((event) => {
    if (event) {
      if (event.reachedEdgeInfo) {
        if (event.reachedEdgeInfo.bottom) {
          Spotlight.focus("orderDetailsPopupCloseButton");
        }
      }
    }
  }, []);

  const onClickCancelReasonItem = useCallback(
    (detailCd, detailCdNm) => {
      dispatch(
        setShowSecondaryPopup(Config.ACTIVE_POPUP.cancelConfirmPopup, {
          secondaryData: {
            mbrNo: userNumber,
            ordNo: popup.data,
            reqChngRsnCd: detailCd,
            reqChngRsn: detailCdNm,
          },
        })
      );

      setCancelReason(detailCdNm);

      setTimeout(() => {
        Spotlight.focus("tPopupBtn2");
      }, 0);
    },
    [dispatch, userNumber, popup.data]
  );

  const onClickSecondaryPopupCancelButton = useCallback(() => {
    dispatch(setHideSecondaryPopup());
    setTimeout(() => {
      Spotlight.focus("cancelReasonListContainer");
    }, 0);
  }, [dispatch]);

  function moveToCancelTab(response) {
    if (response) {
      if (response.retCode === 0) {
        dispatch(setHidePopup());
        reload(true);
      } else {
        console.error("order cancel failed");
      }
    }
  }

  const onClickSecondaryPopupOkButton = useCallback(() => {
    const params = popup.secondaryData;
    const { reqChngRsn: reqRsn } = params;
    const reqTpNm = "Cancel";

    const { prdtId, prdtNm, brndNm, patncNm } = selectedCancelItem;

    dispatch(setHidePopup());
    dispatch(paymentTotalCancel(params, moveToCancelTab));
    dispatch(sendLogOrderChange({ reqRsn, reqTpNm }));

    if (selectedCancelItem)
      dispatch(
        sendLogTotalRecommend({
          contextName: Config.LOG_CONTEXT_NAME.MYORDER,
          messageId: Config.LOG_MESSAGE_ID.BUTTON_CANCEL,
          productId: prdtId,
          productTitle: prdtNm,
          brand: brndNm,
          partner: patncNm,
          reason: cancelReason,
        })
      );
  }, [dispatch, popup, selectedCancelItem, moveToCancelTab]);

  useEffect(() => {
    Spotlight.focus();
  }, [popupVisible]);

  const preventKeyDown = useCallback((event) => {
    if (event.key === "ArrowDown" || event.key === "ArrowUp") {
      event.preventDefault();
      event.stopPropagation();
      return;
    }
  }, []);

  useEffect(() => {
    if (
      popup.secondaryPopup === Config.ACTIVE_POPUP.cancelConfirmPopup &&
      popup.secondaryPopupVisible
    ) {
      document.addEventListener("keydown", preventKeyDown);
    } else {
      document.removeEventListener("keydown", preventKeyDown);
    }

    return () => {
      document.removeEventListener("keydown", preventKeyDown);
    };
  }, [popup.secondaryPopup, popup.secondaryPopupVisible, preventKeyDown]);

  const doSendLogOrderBtnClick = useCallback(
    (btnNm) => {
      dispatch(sendLogOrderBtnClick({ btnNm }));
      sendLogButtonClick(btnNm);
    },
    [buttonTabList, selectedTab]
  );

  useEffect(() => {
    if (
      popup.secondaryPopup === Config.ACTIVE_POPUP.cancelConfirmPopup &&
      popup.secondaryPopupVisible
    ) {
      setTimeout(() => {
        Spotlight.focus("tPopupBtn2");
      }, 0);
    }
  }, [popup.secondaryPopup, popup.secondaryPopupVisible]);

  return (
    <>
      <THeader title={title} />
      <TBody
        className={css.tBody}
        scrollable={false}
        spotlightDisabled={!isOnTop}
      >
        <TVerticalPagenator
          className={css.tVerticalPagenator}
          spotlightId="myOrders_verticalPagenator"
          defaultContainerId={panelInfo?.focusedContainerId}
          onFocusedContainerId={onFocusedContainerId}
          cbChangePageRef={cbChangePageRef}
          onScrollStop={onScrollStop}
          topMargin={40}
          deleteFocus={true}
        >
          <Container
            spotlightId={"myOrders_top_point_area"}
            data-wheel-point={true}
          >
            {buttonTabList && buttonTabList.length > 0 && (
              <TabContainer className={css.tabContainer} id="tabContainer1">
                <TButtonTab
                  contents={buttonTabList}
                  onItemClick={handleButtonTabClick}
                  selectedIndex={selectedTab && selectedTab}
                  listType={LIST_TYPE.medium}
                  spotlightId={SpotlightIds.MY_PAGE_MY_ORDER_TAB_CONTAINER}
                />
                <TDropDown
                  className={classNames(
                    css.dropdown,
                    styleChange === true ? css.myOrdersDropdown : null
                  )}
                  onOpen={handleStyle}
                  onClose={handleStyleOut}
                  onSelect={handleSelectFilter}
                  selectedIndex={dropDownTab}
                  width="small"
                >
                  {filterMethods}
                </TDropDown>
              </TabContainer>
            )}
            <ListContainer
              className={css.listContainer}
              spotlightId={SpotlightIds.MY_PAGE_MY_ORDER_BOX}
              ref={listContainerRef}
            >
              {!isLoading &&
                (selectedTab === 0 ? (
                  orderInfo && orderInfo.length > 0 ? (
                    orderInfo.map((item, index) => (
                      <OrderListCard
                        item={item}
                        key={"order" + index}
                        onClickBuyAgain={onClickBuyAgain}
                        doSendLogOrderBtnClick={doSendLogOrderBtnClick}
                        setSelectedCancelItem={setSelectedCancelItem}
                      />
                    ))
                  ) : (
                    <NoOrderList />
                  )
                ) : cancelOrderInfo && cancelOrderInfo.length > 0 ? (
                  cancelOrderInfo.map((item, index) => (
                    <OrderListCard
                      item={item}
                      key={"cancelOrder" + index}
                      onClickBuyAgain={onClickBuyAgain}
                      cancelItem={true}
                      doSendLogOrderBtnClick={doSendLogOrderBtnClick}
                      setSelectedCancelItem={setSelectedCancelItem}
                    />
                  ))
                ) : (
                  <NoOrderList />
                ))}
              {showGotoTopButton && (
                <TButton
                  type={TYPES.topButton}
                  size={null}
                  data-wheel-point={true}
                  onClick={handleTopButtonClick}
                  ariaLabel="Move to Top, Button"
                />
              )}
            </ListContainer>
          </Container>
        </TVerticalPagenator>
      </TBody>

      {activePopup === Config.ACTIVE_POPUP.orderDetailPopup &&
        orderDetailData && (
          <TPopUp
            kind="orderDetailPopup"
            open={popupVisible}
            onClose={handleClosePopupBtn}
          >
            <div className={css.orderDetailPopupContainer}>
              <div className={css.header}>
                <h3 className={css.headerTitle}>
                  {selectedTab === 0
                    ? $L("ORDER DETAILS")
                    : $L("CANCELLATION DETAILS")}
                </h3>
              </div>

              <div className={css.contentsBody}>
                <TScroller
                  className={css.tScroller}
                  verticalScrollbar="auto"
                  focusableScrollbar={true}
                  onScrollStop={handleStopScrollBar}
                >
                  <div className={css.status}>
                    <p className={css.orderStatus}>
                      {orderDetailData.orderProductInfo[0]?.shptmOrdStNm}
                    </p>
                    <span className={css.arrivingDate}>
                      {/* Arriving January 10 - January 15 */}
                    </span>
                  </div>
                  <div className={css.productWrap}>
                    <CustomImage
                      src={orderDetailData.orderProductInfo[0]?.logoImgPath}
                      alt="Product logo"
                      fallbackSrc={defaultLogoImg}
                    />
                    <p className={css.prdtNm}>
                      {orderDetailData.orderProductInfo[0]?.prdtNm}
                    </p>
                  </div>
                  <div className={css.addressWrap}>
                    <p className={css.addressTitle}>{$L("SHIPPING ADDRESS")}</p>
                    <ul>
                      <li>
                        {orderDetailData.dlvrOdrFnm}{" "}
                        {orderDetailData.dlvrOdrLnm}
                      </li>
                      <li>
                        {orderDetailData.dlvrZpcd} {orderDetailData.dlvrStatNm}
                      </li>
                      <li>{orderDetailData.dlvrCityNm}</li>
                      <li>{orderDetailData.dlvrDtlAddr}</li>
                      <li>
                        {$L("Phone Number")} : {orderDetailData.dlvrCtpt}
                      </li>
                      <li>
                        {$L("Email")}: {orderDetailData.dlvrEmalAddr}
                      </li>
                    </ul>
                    <p className={css.addressTitle}>{$L("BILLING ADDRESS")}</p>

                    <ul>
                      <li>
                        {orderDetailData.bilOdrFnm} {orderDetailData.bilOdrLnm}
                      </li>
                      <li>
                        {orderDetailData.bilZpcd} {orderDetailData.bilStatNm}
                      </li>
                      <li>{orderDetailData.bilCityNm}</li>
                      <li>{orderDetailData.bilDtlAddr}</li>
                      <li>
                        {$L("Phone Number")} : {orderDetailData.bilCtpt}
                      </li>
                      <li>
                        {$L("Email")}: {orderDetailData.bilEmalAddr}
                      </li>
                    </ul>
                  </div>

                  <div className={css.orderSummaryWrap}>
                    <p className={css.orderSummaryTitle}>
                      {$L("ORDER SUMMARY")}
                    </p>
                    <ul className={css.summaryList}>
                      <li className={css.summaryItem}>
                        <span className={css.label}>{$L("Items")}</span>
                        <span className={css.value}>
                          {formatCurrencyValue(
                            totProdPrc,
                            currSign,
                            currSignLoc
                          )}
                        </span>
                      </li>
                      <li className={css.summaryItem}>
                        <span className={css.label}>{$L("Quantity")}</span>
                        <span className={css.value}>
                          {orderDetailData.totProdQty}
                        </span>
                      </li>
                      <li className={css.summaryItem}>
                        <span className={css.label}>
                          {$L("Your Coupon Savings")}
                        </span>
                        <span className={css.value}>
                          {formatCurrencyValue(
                            totDcAmt,
                            currSign,
                            currSignLoc,
                            true
                          )}
                        </span>
                      </li>
                      <li className={css.summaryItem}>
                        <span className={css.label}>
                          {$L("Shipping & Handling")}
                        </span>
                        <span className={css.value}>
                          {formatCurrencyValue(
                            totDlvrAmt,
                            currSign,
                            currSignLoc
                          )}
                        </span>
                      </li>
                      <li className={css.summaryItem}>
                        <span className={css.label}>
                          {$L("TOTAL (before Tax)")}
                        </span>
                        <span className={css.value}>
                          {formatCurrencyValue(
                            ordPmtNoTaxAmt,
                            currSign,
                            currSignLoc
                          )}
                        </span>
                      </li>
                      <li className={css.summaryItem}>
                        <span className={css.label}>
                          {$L("Estimated Sales Tax")}
                        </span>
                        <span className={css.value}>
                          {formatCurrencyValue(
                            ordTotTaxAmt,
                            currSign,
                            currSignLoc
                          )}
                        </span>
                      </li>
                    </ul>
                    <div className={css.totalPrice}>
                      <span className={css.label}>
                        {$L("Item Order Total")}
                      </span>
                      <span className={css.value}>
                        {formatCurrencyValue(
                          ordPmtReqAmt,
                          currSign,
                          currSignLoc
                        )}
                      </span>
                    </div>
                  </div>
                </TScroller>
              </div>

              <div className={css.buttonWrap}>
                <TButton
                  size="large"
                  onClick={handleClosePopupBtn}
                  spotlightId="orderDetailsPopupCloseButton"
                >
                  {$L("CLOSE")}
                </TButton>
              </div>
            </div>
          </TPopUp>
        )}

      {activePopup === Config.ACTIVE_POPUP.orderCancelPopup &&
        cancelReasonInfo &&
        cancelReasonInfo.length > 0 && (
          <TPopUp
            kind="orderCancelPopup"
            open={popupVisible}
            onClose={handleClosePopupBtn}
            hasButton
            button1Text={$L("CLOSE")}
            type="fullscreen"
            onClick={handleClosePopupBtn}
          >
            <div className={css.orderCancelPopupContainerWrap}>
              <div className={css.header}>
                <h3>{$L("SELECT CANCELLATION REASON")}</h3>
              </div>

              <div className={css.orderCancelPopupContainer}>
                <TScroller
                  className={css.orderCancelPopupTScroller}
                  verticalScrollbar="auto"
                >
                  <CancelReasonListContainer
                    spotlightId={"cancelReasonListContainer"}
                  >
                    {cancelReasonInfo
                      .sort((a, b) => a.dispOrd - b.dispOrd)
                      .map((item) => {
                        const { detailCdNm, detailCd, dispOrd, grCd } = item;

                        return (
                          <SpottableListItem
                            key={dispOrd}
                            className={css.cancelReasonItem}
                            onClick={() =>
                              onClickCancelReasonItem(detailCd, detailCdNm)
                            }
                          >
                            {detailCdNm}
                          </SpottableListItem>
                        );
                      })}
                  </CancelReasonListContainer>
                </TScroller>
              </div>
            </div>
          </TPopUp>
        )}

      {activePopup === Config.ACTIVE_POPUP.returnExchangePopup && (
        <TPopUp
          kind="returnExchangePopup"
          open={popupVisible}
          onClose={handleClosePopupBtn}
          hasButton
          button1Text={$L("OK")}
          onClick={handleClosePopupBtn}
        >
          <div className={css.trackPackagePopupContainer}>
            <p className={css.textWrap}>
              <span className={css.textDesc}>
                {$L(
                  "For exchanges and returns, please contact the seller directly. The contact information is provided below."
                )}
              </span>
              <span className={css.textInfo}>
                - {$L("Contact Information")}
                <br />- {data.patncNm} : {data.patncPhnNo}
              </span>
            </p>
          </div>
        </TPopUp>
      )}

      {activePopup === Config.ACTIVE_POPUP.trackPackagePopup && (
        <TPopUp
          kind="trackPackagePopup"
          open={popupVisible}
          onClose={handleClosePopupBtn}
          hasButton
          button1Text={$L("OK")}
          onClick={handleClosePopupBtn}
        >
          <div className={css.trackPackagePopupContainer}>
            <p className={css.textWrap}>
              <span className={css.textDesc}>
                {$L(
                  "You can check the delevery status on ShopLC website using the tracking number below."
                )}
                <span className={css.invTrceId}>
                  {$L("Tracking Number")}: {data.invTrceId}
                </span>
                <span className={css.dlvrMeth}>
                  {$L("Shipping Company")}: {data.dlvrMeth}
                </span>
              </span>
            </p>
            <div className={css.trackPackageQRCode}>
              <div className={css.qrcode}>
                <TQRCode
                  text={data.deliveryUrl}
                  width="360"
                  height="360"
                  isBillingProductVisible
                />
              </div>
            </div>
          </div>
        </TPopUp>
      )}

      {popup.secondaryPopup === Config.ACTIVE_POPUP.cancelConfirmPopup &&
        popup.secondaryPopupVisible && (
          <TPopUp
            kind="cancelConfirmPopup"
            type="fullscreen"
            open={popup.secondaryPopupVisible}
            onClick={onClickSecondaryPopupCancelButton} // press "Cancel" button
            onClose={onClickSecondaryPopupOkButton} // press "OK" button
            hasButton
            button1Text={$L("Cancel")}
            button2Text={$L("OK")}
            hasText
            text={$L("Are you sure you want to cancel this order?")}
          />
        )}
    </>
  );
}
