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

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

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

import { clearSMS } from "../../../actions/appDataActions";
import {
  alertToast,
  setHidePopup,
  setShowPopup,
} from "../../../actions/commonActions";
import {
  clearGetProductCouponDownload,
  getProductCouponDownload,
} from "../../../actions/couponActions";
import { setEventPopClickInfo } from "../../../actions/eventActions";
import { sendLogGNB, sendLogShopByMobile } from "../../../actions/logActions";
import { pushPanel } from "../../../actions/panelActions";
import { startVideoPlayer } from "../../../actions/playActions";
import MobileSendPopUp from "../../../components/MobileSend/MobileSendPopUp";
import TPopUp from "../../../components/TPopUp/TPopUp";
import { launchMembershipApp } from "../../../lunaSend";
import {
  ACTIVE_POPUP,
  LOG_MENU,
  LOG_TP_NO,
  MYINFO_TABS,
  panel_names,
} from "../../../utils/Config";
import { $L, formatLocalDateTime } from "../../../utils/helperMethods";
import css from "../EventPopUpBanner/EventPopUpBanner.module.less";

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

export default function EventPopUpBanner() {
  const dispatch = useDispatch();

  const eventPopInfosData = useSelector(
    (state) => state.event.eventData.eventPopInfo
  );
  const popupVisible = useSelector((state) => state.common.popup.popupVisible);
  const activePopup = useSelector((state) => state.common.popup.activePopup);
  const userNumber = useSelector(
    (state) => state.common?.appStatus.loginUserData.userNumber
  );
  const smsSuccess = useSelector((state) => state.appData.sendSms.retCode);
  const couponDownloadSuccess = useSelector(
    (state) => state.coupon?.couponDownloadSuccess
  );

  const timerRef = useRef();
  const shopByMobileLogRef = useRef(null);
  const defaultFocus = useSelector((state) => state.home.defaultFocus);

  const evntId = eventPopInfosData?.evntId;
  const evntTpCd = eventPopInfosData?.evntTpCd;
  const evntNm = eventPopInfosData?.evntNm;

  const [smsTpCd, setSmsTpCd] = useState("");
  const [eventPopData, setEventPopData] = useState({});

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

  useEffect(() => {
    if (eventPopInfosData) {
      setEventPopData(eventPopInfosData);
      dispatch(setShowPopup(ACTIVE_POPUP.eventPopup));
    }
  }, [dispatch, eventPopInfosData]);

  const handleApply = useCallback(() => {
    if (eventPopData) {
      dispatch(setEventPopClickInfo({ evntApplcnFlag: "Y", evntId }));

      switch (evntTpCd) {
        case "EVT00102": // curation
        case "EVT00104": // curation + prize
        case "EVT00107": {
          // curation + billing coupon
          dispatch(setHidePopup());
          dispatch(
            pushPanel({
              name: panel_names.HOT_PICKS_PANEL,
              panelInfo: {
                curationId: eventPopData?.shptmLnkInfo?.lnkCurationId,
                patnrId: eventPopData?.shptmLnkInfo?.lnkPatnrId,
              },
            })
          );
          break;
        }
        case "EVT00105": {
          // coupon Only
          setSmsTpCd("APP00212");
          dispatch(setShowPopup(ACTIVE_POPUP.smsPopup));

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

          dispatch(sendLogShopByMobile(params));
          shopByMobileLogRef.current = params;
          break;
        }
        case "EVT00108": {
          // Direct+Billng+Coupon
          if (!userNumber) {
            dispatch(setShowPopup(ACTIVE_POPUP.loginPopup));
          } else {
            dispatch(
              getProductCouponDownload({
                mbrNo: userNumber,
                cpnSno: eventPopData?.billCpnSno,
              })
            );
          }
          break;
        }
      }
    }
  }, [eventPopData, userNumber, dispatch]);

  useEffect(() => {
    if (couponDownloadSuccess === 0) {
      dispatch(alertToast($L("Downloading coupon complete.")));
      if (eventPopData && eventPopData?.shptmLnkInfo?.shptmLnkTpCd) {
        dispatch(setHidePopup());
        navigateToLinkByTypeCode();
      }
    }
  }, [couponDownloadSuccess, eventPopData]);

  useEffect(() => {
    if (smsSuccess === 0) {
      setTimeout(() => {
        navigateToLinkByTypeCode();
      }, 3000);
    }
  }, [smsSuccess, activePopup]);

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

  const handleSkip = useCallback(() => {
    if (eventPopInfosData) {
      dispatch(setEventPopClickInfo({ evntApplcnFlag: "N", evntId }));
      dispatch(setHidePopup());
    }

    if (defaultFocus) {
      Spotlight.focus(defaultFocus);
    }
  }, [dispatch, eventPopInfosData, defaultFocus]);

  useEffect(() => {
    timerRef.current = setTimeout(() => {
      Spotlight.focus("tPopupBtn1");
    }, 100);
    return () => clearTimeout(timerRef.current);
  }, []);

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

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

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

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

  return (
    <Container>
      {activePopup === ACTIVE_POPUP.eventPopup && (
        <TPopUp
          kind="eventBannerPopup"
          open={popupVisible}
          onClose={handleSkip}
          onClick={handleApply}
          hasButton
          button1Text={$L("Apply Now")}
          button2Text={$L("Skip")}
          className={css.eventPopup}
        >
          {eventPopInfosData && (
            <p>
              <img src={eventPopInfosData.evntImgUrl} alt={evntNm} />
            </p>
          )}
        </TPopUp>
      )}
      {eventPopData && activePopup === 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"
          )}
          smsTpCd={smsTpCd}
          evntId={eventPopData.evntId}
          patnrId={eventPopData.patnrId}
          shopByMobileLogRef={shopByMobileLogRef}
        />
      )}
      {activePopup === ACTIVE_POPUP.alertPopup && (
        <TPopUp
          kind="textPopup"
          open={popupVisible}
          hasText
          text={$L("Downloading coupon complete.")}
        />
      )}
      {activePopup === 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}
        ></TPopUp>
      )}
    </Container>
  );
}
