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

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

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

import { setHidePopup, setShowPopup } from "../../../actions/commonActions";
import { popPanel } from "../../../actions/panelActions";
import TButton from "../../../components/TButton/TButton";
import TPopUp from "../../../components/TPopUp/TPopUp";
import TQRCode from "../../../components/TQRCode/TQRCode";
import useScrollTo from "../../../hooks/useScrollTo";
import useScrollTopByDistance from "../../../hooks/useScrollTopByDistance";
import * as Config from "../../../utils/Config";
import { $L, getQRCodeUrl } from "../../../utils/helperMethods";
import BillingAddressCard from "../components/BillingAddressCard";
import PaymentCard from "../components/PaymentCard";
import ShippingAddressCard from "../components/ShippingAddressCard";
import Subject from "../components/Subject";
import css from "./InformationContainer.module.less";
import { sendLogTotalRecommend } from "../../../actions/logActions";

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

const BtnSpot = Spottable("p");

const getBtnNmByIndex = (index) => {
  switch (index) {
    case 0:
      return "SHIPPING ADDRESS";
    case 1:
      return "BILLING ADDRESS";
    case 2:
      return "PATMENT METHOD";
    default:
      return "";
  }
};

export default function InformationContainer({
  toggleOfferSideBar,
  toggleOrderSideBar,
  scrollTopBody,
  doSendLogMyInfoEdit,
}) {
  const dispatch = useDispatch();

  const checkoutData = useSelector((state) => state.checkout?.checkoutData);
  const { cursorVisible } = useSelector((state) => state.common.appStatus);
  const { popupVisible, activePopup } = useSelector(
    (state) => state.common.popup
  );

  const auctProdYn = useSelector(
    (state) => state.checkout?.checkoutData?.productList?.[0].auctProdYn
  );
  const auctFinalPriceChgDt = useSelector(
    (state) =>
      state.checkout?.checkoutData?.productList?.[0].auctFinalPriceChgDt
  );
  const totDcAmt = useSelector(
    (state) => state.checkout?.checkoutTotalData?.orderTotalAmtInfo?.totDcAmt
  );
  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 [_, setTab] = useState(0);
  const [prdtData, setPrdtData] = useState({});

  const { getScrollTo } = useScrollTo();
  const { scrollTopByDistance } = useScrollTopByDistance();

  useEffect(() => {
    if (checkoutData) {
      const { patnrId, prdtId, prodQty } = checkoutData.productList[0];
      const prodOptCdCval =
        checkoutData.productList[0].prdtOpt.length > 0
          ? checkoutData.productList[0].prdtOpt[0].prodOptCdCval
          : "";

      const params = {
        patnrId: patnrId,
        prdtId: prdtId,
        prodOptCdCval: prodOptCdCval || "",
        prodQty: prodQty,
      };

      setPrdtData(params);
    }
  }, [checkoutData]);

  const { checkoutUrl } = useMemo(() => {
    const { patnrId, prdtId } = checkoutData.productList[0];
    return getQRCodeUrl({
      serverHOST,
      serverType,
      prdtData,
      entryMenu,
      nowMenu,
      prdtId,
      patnrId,
      index: deviceInfo?.dvcIndex,
    });
  }, [
    serverHOST,
    serverType,
    prdtData,
    nowMenu,
    deviceInfo,
    entryMenu,
    checkoutData,
  ]);

  const handleFocus = useCallback(() => {
    const c = Spotlight.getCurrent();
    const target = c.getAttribute("data-spotlight-id");

    const targetValue = '[data-spotlight-id="' + target + '"]';
    if (cursorVisible) {
      return;
    }
    scrollTopByDistance(
      `[data-marker="scroll-marker"]`,
      targetValue,
      scrollTopBody,
      100
    );
  }, []);

  const handleButtonClick = useCallback(
    (index) => {
      const btnNm = getBtnNmByIndex(index);

      if (btnNm && doSendLogMyInfoEdit) {
        doSendLogMyInfoEdit(btnNm);
      }

      setTab(index);
      dispatch(setShowPopup(Config.ACTIVE_POPUP.qrPopup));
      dispatch(
        sendLogTotalRecommend({
          buttonTitle: `${btnNm} ADD/EDIT`,
          buttonId: `checkout_info_${btnNm.toLowerCase().replace(/\s+/g, "_")}`,
          contextName: Config.LOG_CONTEXT_NAME.CHECKOUT,
          messageId: Config.LOG_MESSAGE_ID.BUTTONCLICK,
        })
      );
    },
    [dispatch, doSendLogMyInfoEdit]
  );

  const handleCancel = useCallback(() => {
    dispatch(setHidePopup());
  }, [dispatch]);

  const handleDone = useCallback(() => {
    dispatch(setHidePopup());
    dispatch(popPanel());
  }, [dispatch, checkoutData]);

  return (
    <>
      <Container className={css.container}>
        <div data-marker="scroll-marker" />
        <Subject title="ORDER ITEMS" />
        <div className={css.markBtn}>
          <BtnSpot
            onClick={toggleOrderSideBar}
            scrollTopBody={scrollTopBody}
            spotlightId="checkout-btn-first"
            onFocus={handleFocus}
          >
            {checkoutData.productList?.length} ITEMS
          </BtnSpot>
        </div>
        <div className={css.listBox}>
          <Subject title="SHIPPING ADDRESS" />
          <TButton
            className={css.editBtn}
            spotlightId="shipping-add-btn"
            onFocus={handleFocus}
            onClick={() => handleButtonClick(0)}
          >
            ADD/EDIT
          </TButton>
          <ShippingAddressCard
            list={checkoutData?.shippingAddressList}
            onFocus={handleFocus}
          />
        </div>
        <div className={css.listBox}>
          <Subject title="BILLING ADDRESS" />
          <TButton
            className={css.editBtn}
            spotlightId="billing-add-btn"
            onFocus={handleFocus}
            onClick={() => handleButtonClick(1)}
          >
            ADD/EDIT
          </TButton>
          <BillingAddressCard
            list={checkoutData?.billingAddressList}
            onFocus={handleFocus}
          />
        </div>
        <div className={css.listBox}>
          <Subject title="PATMENT METHOD" />
          <TButton
            className={css.editBtn}
            spotlightId="payment-add-btn"
            onFocus={handleFocus}
            onClick={() => handleButtonClick(2)}
          >
            ADD/EDIT
          </TButton>
          <PaymentCard list={checkoutData?.cardInfo} />
        </div>
        <div className={css.listBox}>
          <Subject title="OFFERS & PROMOTION" />
          <div className={css.markBtn}>
            <BtnSpot
              onClick={toggleOfferSideBar}
              scrollTopBody={scrollTopBody}
              spotlightId="checkout-btn-fifth"
              onFocus={handleFocus}
            >
              {auctProdYn === "Y" && !auctFinalPriceChgDt ? " - " : totDcAmt}
            </BtnSpot>
          </div>
        </div>
      </Container>

      {/* QR Code */}
      {activePopup === Config.ACTIVE_POPUP.qrPopup && (
        <TPopUp
          kind="qrPopup"
          open={popupVisible}
          onClose={handleCancel}
          className={css.checkoutQRPopup}
        >
          <div className={css.popupContainer}>
            <div className={css.header}>
              <h3>{$L("QR CODE")}</h3>
            </div>

            <div className={css.qrcodeContainer}>
              {checkoutUrl && (
                <div className={css.qrcode}>
                  <TQRCode
                    text={checkoutUrl}
                    isBillingProductVisible
                    width="360"
                    height="360"
                  />
                </div>
              )}
              <h3>
                {$L(
                  "Please update your information and complete the payment on your mobile. By clicking the OK button, you will be redirected to the product details page"
                )}
              </h3>
              <TButton className={css.popupBtn} onClick={handleDone}>
                {$L("OK")}
              </TButton>
            </div>
          </div>
        </TPopUp>
      )}
    </>
  );
}
