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

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

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

import ic_profile from "../../../../../assets/images/icons/ic-profile.svg";
import myinfo_login from "../../../../../assets/images/img-banner-myinfo-login@3x.png";
import { getMyInfoBillingSearch } from "../../../../actions/billingActions";
import { getMyInfoCardSearch } from "../../../../actions/cardActions";
import {
  changeAppStatus,
  launchMembershipApp,
  setHidePopup,
  setShowPopup,
} from "../../../../actions/commonActions";
import { getProductCouponInfo } from "../../../../actions/couponActions";
import {
  sendLogLgAccountLogin,
  sendLogMyInfoEdit,
  sendLogTotalRecommend,
} from "../../../../actions/logActions";
import { getMyInfoShippingSearch } from "../../../../actions/shippingActions";
import TBody from "../../../../components/TBody/TBody";
import TButton, { SIZES, TYPES } from "../../../../components/TButton/TButton";
import TButtonTab, {
  LIST_TYPE,
} from "../../../../components/TButtonTab/TButtonTab";
import THeader from "../../../../components/THeader/THeader";
import TPopUp from "../../../../components/TPopUp/TPopUp";
import TQRCode from "../../../../components/TQRCode/TQRCode";
import { getLoginUserData } from "../../../../lunaSend";
import * as Config from "../../../../utils/Config";
import { $L, getQRCodeUrl } from "../../../../utils/helperMethods";
import css from "../MyInfo/MyInfo.module.less";
import BillingAddressTab from "./MyInfoTabContents/BillingAddressTab/BillingAddressTab";
import CouponTab from "./MyInfoTabContents/CouponTab/CouponTab";
import PaymentTab from "./MyInfoTabContents/PaymentTab/PaymentTab";
import ShippingAddressTab from "./MyInfoTabContents/ShippingAddressTab/ShippingAddressTab";

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

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

const getButtonTabList = () => {
  return [
    $L("PAYMENT"),
    $L("BILLING ADDRESS"),
    $L("SHIPPING ADDRESS"),
    $L("COUPON"),
  ];
};

let buttonTabList = null;

const myInfoTabContents = {
  [Config.MYINFO_TABS.PAYMENT]: PaymentTab,
  [Config.MYINFO_TABS.BILLING_ADDRESS]: BillingAddressTab,
  [Config.MYINFO_TABS.SHIPPING_ADDRESS]: ShippingAddressTab,
  [Config.MYINFO_TABS.COUPON]: CouponTab,
};

export default function MyInfo({ title, cbScrollTo }) {
  if (!buttonTabList) {
    buttonTabList = getButtonTabList();
  }

  const dispatch = useDispatch();

  const { profileNick, userNumber, userId } = useSelector(
    (state) => state.common.appStatus.loginUserData
  );
  const { popupVisible, activePopup } = useSelector(
    (state) => state.common.popup
  );
  const panels = useSelector((state) => state.panels.panels);
  const panelInfos = useSelector(
    (state) => state.panels.panels[panels?.length - 1]
  );
  const cardInfo = useSelector((state) => state.card.cardData?.easyPmtSeq);
  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 [tab, setTab] = useState(Config.MYINFO_TABS.PAYMENT);
  const [loginSuccess, setLoginSuccess] = useState(false);

  const { shippingAddressListUrl, billingAddressListUrl, cardListUrl } =
    useMemo(() => {
      return getQRCodeUrl({
        serverHOST,
        serverType,
        entryMenu,
        nowMenu,
        index: deviceInfo?.dvcIndex,
      });
    }, [serverHOST, serverType, entryMenu, nowMenu, deviceInfo]);

  const qrCodeUrls = useMemo(
    () => [cardListUrl, billingAddressListUrl, shippingAddressListUrl],
    [shippingAddressListUrl, billingAddressListUrl, cardListUrl]
  );

  const SelectedComponent = myInfoTabContents[tab];

  useEffect(() => {
    if (loginSuccess && userNumber) {
      dispatch(
        sendLogLgAccountLogin({
          lginTpNm: "Tv",
          usrNo: userNumber,
        })
      );

      setLoginSuccess(false);
    }
  }, [loginSuccess, userNumber]);

  useEffect(() => {
    if (panelInfos && panelInfos.panelInfo && panelInfos.panelInfo.tabForced) {
      setTab(panelInfos.panelInfo.tabForced);
      Spotlight.focus(
        `[data-spotlight-id="tab-${panelInfos.panelInfo.tabForced}"]`
      );
    }

    if (userNumber) {
      dispatch(getMyInfoCardSearch({ mbrNo: userNumber }));
      dispatch(getMyInfoBillingSearch({ mbrNo: userNumber }));
      dispatch(getMyInfoShippingSearch({ mbrNo: userNumber }));
      dispatch(getProductCouponInfo({ mbrNo: userNumber }));
    }
  }, [userNumber, dispatch, panelInfos]);

  const handleItemClick = useCallback(
    ({ index }) => {
      let btnNm = "";
      if (index === 0) {
        btnNm = "PAYMENT";
      } else if (index === 1) {
        btnNm = "BILLING ADDRESS";
      } else if (index === 2) {
        btnNm = "SHIPPING ADDRESS";
      } else if (index === 3) {
        btnNm = "COUPON";
      }
      dispatch(
        sendLogTotalRecommend({
          tabTitle: btnNm,
          contextName: Config.LOG_CONTEXT_NAME.MYINFO,
          messageId: Config.LOG_MESSAGE_ID.BUTTONCLICK,
        })
      );

      if (index === tab) return;
      setTab(index);
    },
    [tab]
  );

  useEffect(() => {
    if (userNumber) {
      let initFocusedItem;
      if (
        panelInfos &&
        panelInfos.panelInfo &&
        panelInfos.panelInfo.tabForced
      ) {
        initFocusedItem = document.querySelector(
          `[data-spotlight-id="tab-${panelInfos.panelInfo.tabForced}"]`
        );
      } else {
        initFocusedItem = document.querySelector('[data-spotlight-id="tab-0"]');
      }
      Spotlight.focus(initFocusedItem);
    } else {
      Spotlight.focus("mypage-login-button");
    }
  }, [userNumber, panelInfos]);

  const handleLogoutButtonClick = useCallback(() => {
    dispatch(setShowPopup(Config.ACTIVE_POPUP.logoutPopup));
    dispatch(
      sendLogTotalRecommend({
        buttonTitle: "LOG OUT",
        contextName: Config.LOG_CONTEXT_NAME.MYINFO,
        messageId: Config.LOG_MESSAGE_ID.BUTTONCLICK,
      })
    );
  }, [dispatch]);

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

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

    switch (tab) {
      case 0:
        dispatch(getMyInfoCardSearch({ mbrNo: userNumber }));
        break;
      case 1:
        dispatch(getMyInfoBillingSearch({ mbrNo: userNumber }));
        break;
      case 2:
        dispatch(getMyInfoShippingSearch({ mbrNo: userNumber }));
        break;
      default:
        break;
    }
  }, [dispatch, tab, userNumber]);

  const handleLogout = useCallback(() => {
    dispatch(setHidePopup());
    dispatch(launchMembershipApp());

    if (typeof window === "object" && !window.PalmSystem) {
      dispatch(
        changeAppStatus({
          loginUserData: {
            profileNick: "",
            userId: "",
            userNumber: "",
          },
        })
      );
    }
  }, [dispatch]);

  const handleLogin = useCallback(() => {
    dispatch(launchMembershipApp());

    if (typeof window === "object" && !window.PalmSystem) {
      if (serverType === "prd") {
        dispatch(
          changeAppStatus({
            loginUserData: {
              profileNick: "prdtest",
              userId: "prdtest@yopmail.com",
              userNumber: "US2412306099093",
            },
          })
        );
      } else {
        dispatch(
          changeAppStatus({
            loginUserData: {
              profileNick: "twin",
              userId: "twin@t-win.kr",
              userNumber: "US2210240095608",
            },
          })
        );
      }
    }

    setLoginSuccess(true);
  }, [dispatch, serverType]);

  const handleClickEditButton = useCallback(() => {
    let btnNm = "";
    if (tab === 0) {
      btnNm = "PAYMENT";
    } else if (tab === 1) {
      btnNm = "BILLING ADDRESS";
    } else if (tab === 2) {
      btnNm = "SHIPPING ADDRESS";
    }
    dispatch(sendLogMyInfoEdit({ btnNm }));
    dispatch(
      sendLogTotalRecommend({
        tabTitle: btnNm,
        buttonTitle: "ADD/EDIT",
        contextName: Config.LOG_CONTEXT_NAME.MYINFO,
        messageId: Config.LOG_MESSAGE_ID.BUTTONCLICK,
      })
    );
    dispatch(setShowPopup(Config.ACTIVE_POPUP.qrPopup));
  }, [dispatch, tab]);

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

  return (
    <>
      <TBody className={css.tBody} cbScrollTo={cbScrollTo}>
        <Container className={css.myInfoContainer}>
          <div className={css.contentsBox}>
            <div className={css.infoBox}>
              <div className={css.infoTopBox}>
                <img src={ic_profile} className={css.profileImg} />
                <div
                  className={css.textBox}
                  aria-label={
                    userNumber
                      ? "Hi, " + userId.replace(userId, profileNick)
                      : "Please sign in to use LG Shop Time."
                  }
                >
                  {userNumber
                    ? $L("Hi, {userId}").replace("{userId}", profileNick)
                    : $L("Please sign in to use LG Shop Time.")}
                </div>
              </div>
              <div className={css.infoBottomBox}>
                <div
                  className={css.emailBox}
                  aria-label={"Email " + (userNumber ? userId : "")}
                >
                  <div className={css.email}>Email</div>
                  <div className={css.email}>{userNumber ? userId : "-"}</div>
                </div>
                {userNumber ? (
                  <TButton
                    type={TYPES.normal}
                    className={css.logoutButton}
                    onClick={handleLogoutButtonClick}
                    ariaLabel="Logout"
                  >
                    {$L("LOG OUT")}
                  </TButton>
                ) : (
                  <TButton
                    type={TYPES.mypage}
                    className={css.loginButton}
                    onClick={handleLogin}
                    spotlightId={"mypage-login-button"}
                    ariaLabel="SIGN IN (LG Account)"
                  >
                    {$L("SIGN IN (LG Account)")}
                  </TButton>
                )}
              </div>
            </div>
            {userNumber ? (
              <>
                {buttonTabList && buttonTabList.length > 0 && (
                  <TabContainer className={css.tabContainer}>
                    <TButtonTab
                      contents={buttonTabList}
                      onItemClick={handleItemClick}
                      selectedIndex={tab}
                      listType={LIST_TYPE.medium}
                    />
                    {tab !== 3 && (
                      <TButton
                        type={TYPES.mypage}
                        size={SIZES.small}
                        className={css.addBtn}
                        onClick={handleClickEditButton}
                        ariaLabel="add/edit"
                      >
                        {$L("ADD/EDIT")}
                      </TButton>
                    )}
                  </TabContainer>
                )}
                {SelectedComponent && <SelectedComponent />}
              </>
            ) : (
              <div className={css.downloadImg}>
                <img
                  src={myinfo_login}
                  alt="Download Shop Time mobile app image"
                />
              </div>
            )}
          </div>
        </Container>
      </TBody>

      {/* logout */}
      {activePopup === Config.ACTIVE_POPUP.logoutPopup && (
        <TPopUp
          kind="textPopup"
          open={popupVisible}
          hasButton
          button1Text={$L("OK")}
          button2Text={$L("Cancel")}
          hasText
          text={$L("Do you want to logout?")}
          onClose={handleCancel}
          onClick={handleLogout}
        />
      )}

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

            <div className={css.qrcodeContainer}>
              {qrCodeUrls[tab] && (
                <div className={css.qrcode} aria-label="QR CODE image">
                  <TQRCode
                    text={qrCodeUrls[tab]}
                    width="360"
                    height="360"
                    isBillingProductVisible
                  />
                </div>
              )}
              <h3 aria-label="If you want to add or edit your address and payment information, please scan the QR CODE.">
                {$L(
                  "If you want to add or edit your address and payment information, please scan the QR CODE."
                )}
              </h3>
              <TButton
                className={css.popupBtn}
                onClick={handleDone}
                ariaLabel="Close"
              >
                {$L("DONE")}
              </TButton>
            </div>
          </div>
        </TPopUp>
      )}
    </>
  );
}
