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

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

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

import {
  setExitApp,
  setHidePopup,
  setShowPopup,
} from "../../actions/commonActions";
import { registerDevice } from "../../actions/deviceActions";
import { getWelcomeEventInfo } from "../../actions/eventActions";
import { getHomeTerms } from "../../actions/homeActions";
import {
  sendLogGNB,
  sendLogTerms,
  sendLogTotalRecommend,
} from "../../actions/logActions";
import { popPanel, pushPanel } from "../../actions/panelActions";
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 useDebugKey from "../../hooks/useDebugKey";
import * as Config from "../../utils/Config";
import { panel_names } from "../../utils/Config";
import { $L, scaleH, scaleW } from "../../utils/helperMethods";
import css from "./IntroPanel.module.less";

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

export default function IntroPanel({
  children,
  isTabActivated,
  handleCancel,
  spotlightId,
  ...rest
}) {
  delete rest.isTabActivated;
  delete rest.panelInfo;

  useDebugKey({});
  const dispatch = useDispatch();
  const termsData = useSelector((state) => state.home.termsData);
  const { popupVisible, activePopup } = useSelector(
    (state) => state.common.popup
  );
  const eventInfos = useSelector((state) => state.event.eventData);
  const regDeviceData = useSelector((state) => state.device.regDeviceData);
  const regDeviceInfoData = useSelector(
    (state) => state.device.regDeviceInfoData
  );

  const introTermsData = termsData?.data?.terms.filter(
    (item) => item.trmsTpCd === "MST00401" || item.trmsTpCd === "MST00402"
  );
  const webOSVersion = useSelector(
    (state) => state.common.appStatus?.webOSVersion
  );

  const [currentTerms, setCurrentTerms] = useState(null);

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

  const handleTermsClick = useCallback(
    (trmsTpCdList) => {
      if (introTermsData) {
        const selectedTerms = introTermsData.find(
          (term) => term.trmsTpCd === trmsTpCdList
        );

        setCurrentTerms(selectedTerms);
        dispatch(setShowPopup(Config.ACTIVE_POPUP.termsPopup));

        const logTpNo =
          trmsTpCdList === "MST00402"
            ? Config.LOG_TP_NO.TERMS.TEARMS_CONDITIONS
            : Config.LOG_TP_NO.TERMS.PRIVACY_POLICY;
        dispatch(sendLogTerms({ logTpNo }));
      }
    },
    [introTermsData, dispatch]
  );

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

  const handleAgree = useCallback(() => {
    if (introTermsData) {
      const trmsIds = introTermsData.map((term) => term.trmsId);

      

      dispatch(
        registerDevice({
          agreeTerms: trmsIds,
        })
      );

      // dispatch(popPanel(Config.panel_names.INTRO_PANEL));
    }
  }, [introTermsData, dispatch]);

  const handleDisagree = useCallback(() => {
    dispatch(setShowPopup(Config.ACTIVE_POPUP.exitPopup));

    dispatch(sendLogTerms({ logTpNo: Config.LOG_TP_NO.TERMS.DO_NOT_AGREE }));
  }, [dispatch]);

  const onExit = useCallback(() => {
    dispatch(setExitApp());

    dispatch(
      sendLogTotalRecommend({
        contextName: Config.LOG_CONTEXT_NAME.SHOPTIME,
        messageId: Config.LOG_MESSAGE_ID.VIEW_CHANGE,
        visible: false,
      })
    );
  }, [dispatch]);

  const onCancel = useCallback(() => {
    if (activePopup === null) {
      dispatch(setShowPopup(Config.ACTIVE_POPUP.exitPopup));
    }
  }, [dispatch]);

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

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

  useEffect(() => {
    if (regDeviceData && regDeviceData.retCode === 0) {
      dispatch(getWelcomeEventInfo());
    }
  }, [dispatch, regDeviceData]);

  useEffect(() => {
    if (regDeviceInfoData && regDeviceInfoData.retCode === 0) {
      dispatch(setHidePopup());
      dispatch(popPanel(panel_names.INTRO_PANEL));
    }
  }, [dispatch, regDeviceInfoData]);

  useEffect(() => {
    if (eventInfos && Object.keys(eventInfos).length > 0 && webOSVersion) {
      let displayWelcomeEventPanel = false;

      if (
        eventInfos?.welcomeEventFlag === "Y" ||
        (eventInfos?.welcomeBillCpnEventFlag === "Y" &&
          Number(webOSVersion) >= 6)
      ) {
        displayWelcomeEventPanel = true;
      }

      dispatch(popPanel(panel_names.INTRO_PANEL));
      dispatch(sendLogTerms({ logTpNo: Config.LOG_TP_NO.TERMS.AGREE }));

      if (displayWelcomeEventPanel) {
        dispatch(
          pushPanel({
            name: panel_names.WELCOME_EVENT_PANEL,
            panelInfo: { eventInfos: eventInfos },
          })
        );
      }
    }
  }, [eventInfos, webOSVersion]);

  const description = $L(
    "Check out more LIVE SHOWS now and enjoy shopping at Shop Time's special price on your TV by agreeing to the LG TV Shopping Terms and Conditions."
  );
  const title = "welcome to shoptime!";
  delete rest.isOnTop;
  return (
    <Region title={title + description}>
      <TPanel
        className={css.panel}
        isTabActivated={false}
        handleCancel={onCancel}
        spotlightId={spotlightId}
      >
        <Container {...rest} className={css.introLayout}>
          <div className={css.title}>
            {$L("Welcome to ")}
            <span className={css.txtPoint}>
              {$L("Sh")}
              <span className={css.pointColor}>{$L("o")}</span>
              {$L("p Time !")}
            </span>
          </div>
          <div className={css.description}>{description}</div>
          <div className={css.termsItemsLayer}>
            <TButton
              onClick={() => handleTermsClick("MST00402")}
              type={TYPES.terms}
              className={css.termsButton}
            >
              {$L("Terms & Conditions")}
            </TButton>
            <TButton
              onClick={() => handleTermsClick("MST00401")}
              type={TYPES.terms}
              className={css.termsButton}
            >
              {$L("Privacy Policy")}
            </TButton>
          </div>
          <div className={css.bottomBtnLayer}>
            <TButton
              onClick={handleAgree}
              spotlightId="introTermsAgree"
              type={TYPES.agree}
            >
              {$L("Agree")}
            </TButton>
            <TButton onClick={handleDisagree} type={TYPES.agree}>
              {$L("Do Not Agree")}
            </TButton>
          </div>
        </Container>
      </TPanel>

      {/* TERMS */}
      {activePopup === Config.ACTIVE_POPUP.termsPopup && (
        <TPopUp
          kind="introTermsPopup"
          open={popupVisible}
          onClose={onClose}
          hasButton
          button1Text={$L("OK")}
        >
          {currentTerms && (
            <div className={css.introTermsConts}>
              <TButtonTab
                className={css.tab}
                selectedIndex={0}
                contents={
                  currentTerms.trmsTpCd === "MST00401"
                    ? [$L("Privacy Policy")]
                    : [$L("Terms & Conditions")]
                }
                spotlightDisabled={true}
                role="button"
              />
              <TButtonScroller
                boxHeight={scaleH(300)}
                width={scaleW(980)}
                className={css.termsDescription}
              >
                <div
                  className={css.termsDesc}
                  dangerouslySetInnerHTML={{
                    __html: currentTerms && currentTerms.trmsCntt,
                  }}
                />
              </TButtonScroller>
            </div>
          )}
        </TPopUp>
      )}

      {/* DO NOT AGREE */}
      {activePopup === Config.ACTIVE_POPUP.exitPopup && (
        <TPopUp
          kind="exitPopup"
          open={popupVisible}
          onExit={onExit}
          onClose={onClose}
          hasButton
          button1Text={$L("Exit")}
          button2Text={$L("Cancel")}
          hasText
          title={$L("Exit Shop Time")}
          text={$L("Are you sure you want to exit Shop Time?")}
        />
      )}
    </Region>
  );
}
