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

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

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

import {
  alertToast,
  launchMembershipApp,
  setHidePopup,
  setShowPopup,
} from "../../actions/commonActions";
import {
  clearGetProductCouponDownload,
  getProductCouponDownload,
} from "../../actions/couponActions";
import {
  clearEventIssuedStatusSuccess,
  getEventIssuedStaus,
  getWelcomeEventInfo,
} from "../../actions/eventActions";
import { sendLogGNB, sendLogShopByMobile } from "../../actions/logActions";
import { popPanel, pushPanel } from "../../actions/panelActions";
import { startVideoPlayer } from "../../actions/playActions";
import MobileSendPopUp from "../../components/MobileSend/MobileSendPopUp";
import TButton, { TYPES } from "../../components/TButton/TButton";
import TButtonScroller from "../../components/TButtonScroller/TButtonScroller";
import TButtonTab from "../../components/TButtonTab/TButtonTab";
import TPanel from "../../components/TPanel/TPanel";
import TPopUp from "../../components/TPopUp/TPopUp";
import * as Config from "../../utils/Config";
import {
  $L,
  formatLocalDateTime,
  scaleH,
  scaleW,
} from "../../utils/helperMethods";
import css from "../WelcomeEventPanel/WelcomeEventPanel.module.less";

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

const getShopTpNm = (evntTpCd) => {
  switch (evntTpCd) {
    case "EVT00101":
      return "coupon";
    case "EVT00103":
      return "prizeevent";
    default:
      return "";
  }
};

const WelcomeEventPanel = ({ spotlightId }) => {
  const dispatch = useDispatch();

  const eventDatas = useSelector((state) => state.event.eventData);
  const eventRetCode = useSelector((state) => state.event?.retCode);
  const eventInfo = useSelector((state) => state.event.eventData?.eventInfo);
  const shptmLnkInfo = useSelector(
    (state) => state.event?.eventData?.eventInfo?.shptmLnkInfo
  );
  const billCpnSno = useSelector(
    (state) => state.event?.eventData?.eventInfo?.billCpnSno
  );
  const userNumber = useSelector(
    (state) => state.common?.appStatus.loginUserData.userNumber
  );
  const { popupVisible, activePopup } = useSelector(
    (state) => state.common.popup
  );
  const eventIssuedStatusSuccess = useSelector(
    (state) => state.event.eventIssuedStatusSuccess
  );
  const regDeviceInfoData = useSelector(
    (state) => state.device.regDeviceInfoData
  );
  const loadingComplete = useSelector((state) => state.common?.loadingComplete);
  const couponDownloadSuccess = useSelector(
    (state) => state.coupon?.couponDownloadSuccess
  );
  const webOSVersion = useSelector(
    (state) => state.common.appStatus?.webOSVersion
  );

  const shopByMobileLogRef = useRef(null);
  const timerRef = useRef();

  const { trmsCntt, evntImgUrl, trmsBtnExpsFlag, evntTpCd, evntId } =
    eventDatas.eventInfo || {};

  const handleTermsClick = useCallback(() => {
    if (eventDatas && trmsCntt) {
      dispatch(setShowPopup(Config.ACTIVE_POPUP.termsPopup));
    }
  }, [dispatch, eventDatas, trmsCntt]);

  const handleSkip = useCallback(() => {
    dispatch(popPanel(Config.panel_names.WELCOME_EVENT_PANEL));
  }, [dispatch]);

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

  const handleAgree = useCallback(() => {
    if (eventDatas && evntTpCd === "EVT00106") {
      // WELCOME + BILLING
      if (!userNumber) {
        dispatch(setShowPopup(Config.ACTIVE_POPUP.loginPopup));
      } else {
        // 상품 쿠폰 다운로드 (IF-LGSP-318)
        dispatch(
          getProductCouponDownload({
            mbrNo: userNumber,
            cpnSno: billCpnSno,
          })
        );
      }
    } else {
      if (eventDatas && evntTpCd && evntId) {
        dispatch(getEventIssuedStaus({ evntTpCd, evntId }));
      }
    }
  }, [billCpnSno, dispatch, eventDatas, evntId, evntTpCd, userNumber]);

  useEffect(() => {
    dispatch(sendLogGNB(Config.LOG_MENU.WELCOME_EVENT));
  }, []);

  useEffect(() => {
    if (eventIssuedStatusSuccess === 0 && eventIssuedStatusSuccess !== null) {
      dispatch(setShowPopup(Config.ACTIVE_POPUP.smsPopup));

      const params = {
        befPrice: "",
        curationId: eventInfo?.shptmLnkInfo?.lnkCurationId ?? "",
        curationNm: "",
        evntId: eventInfo?.evntId ?? "",
        evntNm: eventInfo?.evntNm ?? "",
        lastPrice: "",
        lgCatCd: eventInfo?.shptmLnkInfo?.lnkLgCatCd ?? "",
        lgCatNm: "",
        liveFlag: "N",
        locDt: formatLocalDateTime(new Date()),
        logTpNo: Config.LOG_TP_NO.SHOP_BY_MOBILE.SHOP_BY_MOBILE,
        mbphNoFlag: "N",
        patncNm: "",
        patnrId: eventInfo?.shptmLnkInfo?.lnkPatnrId ?? "",
        prdtId: "",
        prdtNm: "",
        revwGrd: "",
        rewdAplyFlag: "N",
        shopByMobileFlag: "Y",
        shopTpNm: getShopTpNm(evntTpCd),
        showId: "",
        showNm: "",
        trmsAgrFlag: "N",
        tsvFlag: "N",
      };

      dispatch(sendLogShopByMobile(params));
      shopByMobileLogRef.current = params;
    } else if (
      eventIssuedStatusSuccess !== null &&
      eventIssuedStatusSuccess !== 0
    ) {
      dispatch(setShowPopup(Config.ACTIVE_POPUP.alertPopup));
    }
  }, [
    dispatch,
    eventInfo?.evntId,
    eventInfo?.evntNm,
    eventInfo?.shptmLnkInfo?.lnkCurationId,
    eventInfo?.shptmLnkInfo?.lnkLgCatCd,
    eventInfo?.shptmLnkInfo?.lnkPatnrId,
    eventIssuedStatusSuccess,
    evntTpCd,
  ]);

  const onClose = useCallback(() => {
    dispatch(setHidePopup());
    dispatch(clearEventIssuedStatusSuccess());
    Spotlight.focus("agree");
  }, [dispatch]);

  const handleTermsClose = useCallback(() => {
    dispatch(setHidePopup());
    Spotlight.focus("terms-button");
  }, [dispatch]);

  const navigateToLinkByTypeCode = useCallback(() => {
    if (shptmLnkInfo) {
      switch (shptmLnkInfo.shptmLnkTpCd) {
        case "EVT00201":
          break;
        case "EVT00202":
          dispatch(
            pushPanel({
              name: Config.panel_names.FEATURED_BRANDS_PANEL,
              panelInfo: { from: "gnb", patnrId: shptmLnkInfo?.lnkPatnrId },
            })
          );
          break;
        case "EVT00203":
          dispatch(pushPanel({ name: Config.panel_names.TRENDING_NOW_PANEL }));
          break;
        case "EVT00204":
          pushPanel({
            name: Config.panel_names.HOT_PICKS_PANEL,
            panelInfo: {
              curationId: shptmLnkInfo?.lnkCurationId,
              patnrId: shptmLnkInfo?.lnkPatnrId,
            },
          });
          break;
        case "EVT00205":
          dispatch(
            pushPanel({
              name: Config.panel_names.ON_SALE_PANEL,
              panelInfo: { lgCatCd: shptmLnkInfo?.lnkLgCatCd },
            })
          );
          break;
        case "EVT00206":
          dispatch(
            pushPanel({
              name: Config.panel_names.CATEGORY_PANEL,
              panelInfo: {
                lgCatCd: shptmLnkInfo?.lnkLgCatCd,
              },
            })
          );
          break;
        case "EVT00207":
          dispatch(
            pushPanel({
              name: Config.panel_names.DETAIL_PANEL,
              panelInfo: {
                patnrId: shptmLnkInfo?.lnkPatnrId,
                prdtId: shptmLnkInfo?.lnkPrdtId,
              },
            })
          );
          break;
        case "EVT00208":
          dispatch(
            startVideoPlayer({
              modal: false,
              patnrId: shptmLnkInfo?.lnkPatnrId,
              showId: shptmLnkInfo?.lnkBrdcId,
              shptmBanrTpNm: "VOD",
            })
          );
          break;
        case "EVT00209":
          dispatch(
            pushPanel({
              name: Config.panel_names.THEME_CURATION_PANEL,
              panelInfo: {
                curationId: shptmLnkInfo?.lnkCurationId,
              },
            })
          );
          break;
        case "EVT00210":
          // need editing
          dispatch(
            pushPanel({
              name: Config.panel_names.MY_PAGE_PANEL,
              panelInfo: { menuNm: "My Info", menuOrd: 3 },
            })
          );
          break;
      }
    }
    return;
  }, [shptmLnkInfo, dispatch]);

  useEffect(() => {
    if (eventRetCode === 0) {
      timerRef.current = setTimeout(() => {
        Spotlight.focus("agree");
      }, 0);
    }
    return () => clearTimeout(timerRef.current);
  }, [eventRetCode]);

  const welcomeStyle = useMemo(
    () => ({ backgroundImage: `url(${evntImgUrl})` }),
    [evntImgUrl]
  );

  useEffect(() => {
    if (!eventInfo) {
      dispatch(getWelcomeEventInfo());
    }
  }, [dispatch, eventInfo]);

  useEffect(() => {
    // 기존회원 && 이벤트 대상이 아닐 경우
    if (
      eventDatas.welcomeEventFlag === "N" &&
      eventDatas.welcomeBillCpnEventFlag !== "Y" &&
      loadingComplete
    ) {
      dispatch(popPanel(Config.panel_names.WELCOME_EVENT_PANEL));
    }
  }, [eventDatas, dispatch, loadingComplete]);

  const toastAlertMessage = useCallback(() => {
    dispatch(alertToast($L("Downloading coupon complete.")));
  }, [dispatch]);

  const closePanelAndNavigate = useCallback(() => {
    dispatch(popPanel(Config.panel_names.WELCOME_EVENT_PANEL));
    if (shptmLnkInfo?.shptmLnkTpCd) {
      navigateToLinkByTypeCode();
    }
  }, [dispatch, navigateToLinkByTypeCode, shptmLnkInfo]);

  useEffect(() => {
    // EVT00101 & EVT00103 Welcome & Welcome+Priczes 이벤트
    if (regDeviceInfoData && regDeviceInfoData?.retCode === 0) {
      if (activePopup === null) {
        closePanelAndNavigate();
      }
    }
    return;
  }, [activePopup, closePanelAndNavigate, regDeviceInfoData]);

  useEffect(() => {
    // EVT00106 Welcome Billing Coupon Event 이벤트
    if (couponDownloadSuccess === 0) {
      if (webOSVersion && Number(webOSVersion) >= 6) {
        toastAlertMessage();
        closePanelAndNavigate();
      }
    }
  }, [
    closePanelAndNavigate,
    couponDownloadSuccess,
    toastAlertMessage,
    webOSVersion,
  ]);

  useEffect(() => {
    return () => {
      dispatch(clearGetProductCouponDownload());
      dispatch(setHidePopup());
    };
  }, [dispatch]);

  const getEvntErrorMsg = useMemo(() => {
    if (eventIssuedStatusSuccess === 600) {
      return $L("This device had received first time coupon.");
    } else if (eventIssuedStatusSuccess === 601) {
      return $L("There is no coupon.");
    } else return;
  }, [eventIssuedStatusSuccess]);

  return (
    <>
      {eventDatas?.eventInfo && (
        <TPanel
          className={css.welcomePanel}
          isTabActivated={false}
          spotlightId={spotlightId}
        >
          <Container className={css.eventLayout} style={welcomeStyle}>
            <div className={css.termsBtn}>
              {trmsBtnExpsFlag === "Y" && (
                <TButton
                  onClick={handleTermsClick}
                  className={css.termsBtn}
                  type={TYPES.terms}
                  spotlightId={"terms-button"}
                >
                  {$L("Terms & Conditions")}
                </TButton>
              )}
            </div>
            <div className={css.bottomBtnLayer}>
              <TButton
                className={css.agreeBtn}
                onClick={handleAgree}
                spotlightId="agree"
                type={TYPES.agree}
              >
                {$L("Agree")}
              </TButton>
              <TButton
                onClick={handleSkip}
                className={css.agreeBtn}
                type={TYPES.agree}
              >
                {$L("Skip")}
              </TButton>
            </div>
          </Container>
        </TPanel>
      )}
      {eventDatas?.eventInfo &&
        activePopup === Config.ACTIVE_POPUP.termsPopup && (
          <TPopUp
            kind="introTermsPopup"
            open={popupVisible}
            onClose={handleTermsClose}
            hasButton
            button1Text="OK"
            title={$L("Terms & Conditions")}
            className={css.termsPopup}
          >
            <div className={css.introTermsConts}>
              <TButtonTab
                className={css.tab}
                selectedIndex={0}
                contents={[$L("Terms & Conditions")]}
                spotlightDisabled
              />

              <TButtonScroller
                boxHeight={scaleH(300)}
                width={scaleW(980)}
                className={css.termsDescription}
              >
                <div
                  className={css.termsDesc}
                  dangerouslySetInnerHTML={{
                    __html: eventDatas && trmsCntt,
                  }}
                />
              </TButtonScroller>
            </div>
          </TPopUp>
        )}
      {activePopup === Config.ACTIVE_POPUP.loginPopup && (
        <TPopUp
          kind="textPopup"
          hasText
          open={popupVisible}
          text={$L("Would you like to sign in?")}
          hasButton
          button1Text={$L("OK")}
          button2Text={$L("CANCEL")}
          onClick={handleLogin}
          onClose={onClose}
        />
      )}
      {activePopup === Config.ACTIVE_POPUP.smsPopup && (
        <MobileSendPopUp
          open={popupVisible}
          onClose={onClose}
          title={$L("Send To Mobile")}
          subTitle={$L(
            "Enter your mobile number to receive detailed information via SMS"
          )}
          evntTpCd={evntTpCd}
          evntId={evntId}
          shopByMobileLogRef={shopByMobileLogRef}
        />
      )}
      {activePopup === Config.ACTIVE_POPUP.alertPopup && (
        <TPopUp
          kind="textPopup"
          open={popupVisible}
          hasText
          text={getEvntErrorMsg}
          onClick={onClose}
          hasButton
          button1Text={$L("OK")}
        />
      )}
    </>
  );
};

export default WelcomeEventPanel;
