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

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

import Spotlight from "@enact/spotlight";
import { Job } from "@enact/core/util";
import classnames from "classnames";

import {
  changeLocalSettings,
  launchMembershipApp,
  setExitApp,
  setHidePopup,
  setShowPopup,
  getTermsAgreeYn,
  updateOptionalTermsAgreement,
} from "../../../../actions/commonActions";
import {
  setMyTermsWithdraw,
  setMyPageTermsAgree,
} from "../../../../actions/myPageActions";
import TBody from "../../../../components/TBody/TBody";
import TButton, { TYPES } from "../../../../components/TButton/TButton";
import TButtonScroller from "../../../../components/TButtonScroller/TButtonScroller";
import TButtonTab from "../../../../components/TButtonTab/TButtonTab";
import THeader from "../../../../components/THeader/THeader";
import TPopUp from "../../../../components/TPopUp/TPopUp";
import { initialLocalSettings } from "../../../../reducers/localSettingsReducer";
import * as Config from "../../../../utils/Config";
import { $L, scaleH, scaleW } from "../../../../utils/helperMethods";
import css from "./TermsOfService.module.less";
import TCheckBoxSquare from "../../../../components/TCheckBox/TCheckBoxSquare";

export default function TermsOfService({ title, cbScrollTo }) {
  const [selectedTab, setSelectedTab] = useState(0);
  const [trmsTpCd, setTrmsTpCd] = useState("MST00401");
  const [tabList, setTabList] = useState([]);
  const [trmsCdList, setTrmsCdList] = useState([]);
  const [closePopUp, setClosePopUp] = useState(false);
  const [resetScroll, setResetScroll] = useState(false);
  const [agreePopup, setAgreePopup] = useState(false);
  const [isOptionalChecked, setIsOptionalChecked] = useState(optionalTermsAgree);
  const [optionalDisagreePopupOpen, setOptionalDisagreePopupOpen] =
    useState(false);
  const [showCheckboxAlert, setShowCheckboxAlert] = useState(false);
  const agreePopupTimeoutRef = useRef(null);

  const { popupVisible } = useSelector((state) => state.common?.popup);
  const { optionalTermsAgree } = useSelector((state) => state.common);
  console.log("[TermsOfService] 현재 optionalTermsAgree 상태:", optionalTermsAgree);
  const termsData = useSelector((state) => state.home.termsData);
  const empTermsData = useSelector((state) => state.emp.empTermsData);
  const webOSVersion = useSelector(
    (state) => state.common.appStatus.webOSVersion
  );
  const [spotlightDisabled, setSpotlightDisabled] = useState(true);
  const [termsList, setTermsList] = useState([]);
  const termsListRef = useRef(termsList);
  const [localOptionalTermsAgree, setLocalOptionalTermsAgree] = useState(false);

  const dispatch = useDispatch();

  const focusJob = useRef(null);

  useEffect(() => {
    return () => {
      if (agreePopupTimeoutRef.current) {
        clearTimeout(agreePopupTimeoutRef.current);
      }
    };
  }, []);

  // ✅ fetchCurrentUserHomeTerms 호출 제거 - TV 환경에서 서버 동기화 지연 방지

  useEffect(() => {
    console.log("[TermsOfService] optionalTermsAgree 상태 변경:", optionalTermsAgree);
    setLocalOptionalTermsAgree(optionalTermsAgree);
    setIsOptionalChecked(optionalTermsAgree);
  }, [optionalTermsAgree]);

  useEffect(() => {
    // console.log(
    //   "[TermsOfService] termsData:",
    //   JSON.stringify(termsData, null, 2)
    // );
    // console.log(
    //   "[TermsOfService] empTermsData:",
    //   JSON.stringify(empTermsData, null, 2)
    // );
    const newTabList = [];
    const tempList = [];
    const newTrmsCdList = [];

    if (termsData && termsData.data && termsData.data.terms) {
      termsData.data.terms.forEach((term) => {
        newTabList.push(term.trmsNm);

        tempList.push({
          termsName: term.trmsNm,
          termsContents: term.trmsCntt,
          termsId: term.trmsId,
          trmsTpCd: term.trmsTpCd,
        });
      });
    }

    if (
      webOSVersion &&
      Number(webOSVersion) >= 6 &&
      empTermsData &&
      empTermsData.terms
    ) {
      empTermsData.terms.forEach((term) => {
        newTabList.push(term.termsTypeName);

        tempList.push({
          termsContents: term.termContent,
          termsId: term.termsID,
          trmsTpCd: term.trmsTpCd,
        });
      });
    }

    setTabList(newTabList);
    setTermsList(tempList);
    // console.log(
    //   "[TermsOfService] Final termsList:",
    //   JSON.stringify(tempList, null, 2)
    // );
    setTrmsCdList(newTrmsCdList);

    setSpotlightDisabled(false);
  }, [termsData, empTermsData, webOSVersion]);

  useEffect(() => {
    termsListRef.current = termsList;
  }, [termsList]);

  // ✅ getTermsAgreeYn 호출 제거 - TV 환경에서 서버 동기화 지연 방지
  // useEffect(() => {
  //   if (termsData && termsData.data && termsData.data.terms) {
  //     dispatch(getTermsAgreeYn());
  //   }
  // }, [termsData, dispatch]);

  const handleItemClick = useCallback(
    ({ index }) => {
      setSelectedTab(index);

      setResetScroll(true);
    },
    [trmsTpCd]
  );

  // 1단계: 포커스 대상 결정 함수 생성
  const getOptionalTermsFocusTarget = useCallback(() => {
    console.log("[TermsOfService] 포커스 대상 결정:", {
      optionalTermsAgree,
      isOptionalChecked
    });

    if (optionalTermsAgree) {
      console.log("[TermsOfService] → optional-disagree-button (이미 동의함)");
      return "optional-disagree-button"; // 이미 동의한 경우
    }

    //미동의 상태에서 체크박스 선택 여부에 따라 결정
    if (isOptionalChecked) {
      console.log("[TermsOfService] → optional-agree-button (체크박스 선택됨)");
      return "optional-agree-button"; // 체크박스 선택됨 → Agree 버튼으로
    } else {
      console.log("[TermsOfService] → optional-agree-checkbox (체크박스 미선택)");
      return "optional-agree-checkbox"; // 체크박스 미선택 → 체크박스로
    }
  }, [optionalTermsAgree, isOptionalChecked]);

  useEffect(() => {
    // 이전 Job 정리
    if (focusJob.current) {
      focusJob.current.stop();
    }
    // 이전 타이머 정리
    // if (timeoutRef.current) {
    //   clearTimeout(timeoutRef.current);
    //   timeoutRef.current = null;
    // }
    if (
      termsList.length > 0 &&
      termsList[selectedTab]?.trmsTpCd === "MST00405"
    ) {
      focusJob.current = new Job(() => {
        // 초기 포커스: 체크박스로 이동
        const initialFocusTarget = getOptionalTermsFocusTarget();
        Spotlight.focus(initialFocusTarget);

        // 0.5초 후 Agree 버튼으로 포커스 이동 (미동의 상태이고 체크박스 미선택인 경우)
        if (!optionalTermsAgree && !isOptionalChecked) {
          setTimeout(() => {
            console.log("[TermsOfService] 1.5초 후 Agree 버튼으로 포커스 이동");
            Spotlight.focus("optional-agree-button");
          }, 300);
        }
      });
      focusJob.current.startAfter(100);
    }
    return () => {
      if (focusJob.current) {
        focusJob.current.stop();
      };
      // if (timeoutRef.current) {
      //   clearTimeout(timeoutRef.current);
      //   timeoutRef.current = null;
      // }
    };
  }, [selectedTab, termsList, optionalTermsAgree, isOptionalChecked, getOptionalTermsFocusTarget]); // 3단계: 의존성 배열 업데이트

  useEffect(() => {
    if (!spotlightDisabled) {
      Spotlight.focus("tab-0");
    }
  }, [spotlightDisabled]);

  useEffect(() => {
    if (resetScroll) {
      setResetScroll(false);
    }
  }, [resetScroll]);

  const handleDisagree = useCallback(() => {
    dispatch(setShowPopup(Config.ACTIVE_POPUP.exitPopup));
  }, [dispatch]);

  // 엘지 앱으로 이동
  const handleLGAccount = useCallback(() => {
    dispatch(launchMembershipApp());
  }, [dispatch]);

  function withdrawTermsCallback(response) {
    if (response) {
      if (response.retCode === 0) {
        setClosePopUp(true);

        setTimeout(() => {
          setClosePopUp(false);
          dispatch(changeLocalSettings(initialLocalSettings));
          dispatch(setExitApp());
        }, 3000);
      } else {
        console.error("network error", response);
      }
    }
  }

  // 약관 철회
  const onExit = useCallback(() => {
    dispatch(setHidePopup());
    dispatch(
      setMyTermsWithdraw(
        {
          mandatoryIncludeYn: "Y",
          termsList: ["MST00401", "MST00402"],
        },
        withdrawTermsCallback
      )
    );
  }, [dispatch]);

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

  const handleOptionalCheckboxToggle = useCallback(
    ({ selected }) => {
      if (optionalTermsAgree) return;
      setIsOptionalChecked(selected);
      // 포커스 이동은 useEffect의 getOptionalTermsFocusTarget에서 통합 처리
      console.log("[TermsOfService] 체크박스 토글:", { selected });
    },
    [optionalTermsAgree]
  );

  const handleOptionalAgree = useCallback(() => {
    // console.log(
    //   "handleOptionalAgree called with isChecked:",
    //   isOptionalChecked
    // );
    // if (isOptionalChecked) {
    const firstThreeTermIds = termsList
      .slice(0, 3)
      .map((term) => term.termsId)
      .filter(Boolean);

    if (firstThreeTermIds.length > 0) {
      const payload = { termsList: firstThreeTermIds, notTermsList: [] };
      // console.log("Dispatching setMyPageTermsAgree with payload:", payload);
      dispatch(
        setMyPageTermsAgree(payload, (response) => {
          // console.log("setMyPageTermsAgree callback response:", response);
          if (response.retCode === "000" || response.retCode === 0) {
            setLocalOptionalTermsAgree(true);
            setIsOptionalChecked(true);
            console.log("Optional terms agreement successful.");

            // ✅ IntroPanel과 동일한 방식으로 Redux 상태 직접 업데이트 (API 호출 없이)
            dispatch(updateOptionalTermsAgreement(true));

            setAgreePopup(true);

            if (agreePopupTimeoutRef.current) {
              clearTimeout(agreePopupTimeoutRef.current);
            }

            agreePopupTimeoutRef.current = setTimeout(() => {
              setAgreePopup(false);
            }, 3000);
          } else {
            console.error("Optional terms agreement failed:", response);
          }
        })
      );
    } else {
      // console.log("No terms found to agree to.");
    }
    // } else {
    //   console.log("Checkbox not checked, not proceeding with agreement.");
    //   setShowCheckboxAlert(true);
    // }
  }, [dispatch, termsList, isOptionalChecked]);

  const handleOptionalDisagree = useCallback(() => {
    if (agreePopup === false) {
      setOptionalDisagreePopupOpen(true);
    }
  }, [agreePopup]);

  const confirmOptionalDisagree = useCallback(() => {
    const currentTermsList = termsListRef.current;
    // console.log("optionalTermsAgree:", currentTermsList);
    const optionalTerm = currentTermsList.find(
      (term) => term.trmsTpCd === "MST00405"
    );
    // console.log("optionalTerm:", JSON.stringify(optionalTerm, null, 2));

    // if (optionalTerm) {
    //   console.log("optionalTerm.termsId:", optionalTerm.termsId);
    // }

    if (optionalTerm && optionalTerm.termsId) {
      const payload = {
        mandatoryIncludeYn: "N",
        termsList: [optionalTerm.termsId],
      };
      // console.log("Dispatching setMyTermsWithdraw with payload:", payload);
      // 선택약관 철회
      dispatch(
        setMyTermsWithdraw(payload, (response) => {
          // console.log("setMyTermsWithdraw callback response:", response);
          if (response.retCode === "000" || response.retCode === 0) {
            console.log("Optional terms withdrawal successful.");
            // ✅ fetchCurrentUserHomeTerms 호출 제거하고 Redux 상태 직접 업데이트
            dispatch(updateOptionalTermsAgreement(false));
            setLocalOptionalTermsAgree(false);
            setIsOptionalChecked(false);
          } else {
            console.error("Optional terms withdrawal failed:", response);
          }
          setOptionalDisagreePopupOpen(false);
        })
      );
    } else {
      // console.log("No optional term found to disagree.");
      setOptionalDisagreePopupOpen(false);
    }
  }, [dispatch]);

  const onCancelDisagree = useCallback(() => {
    // setDisagreeConfirmOpen(false);
  }, []);

  const isOptionalTab = useMemo(() => {
    return termsList[selectedTab]?.trmsTpCd === "MST00405";
  }, [termsList, selectedTab]);

  const termsAriaLabel = useMemo(() => {
    if (!termsList || !termsList[selectedTab]) return "";

    const termsName = termsList[selectedTab]?.termsName || "";
    const termsContents = termsList[selectedTab]?.termsContents || "";

    const cleanTermsName = termsName.replace(/(<([^>]+)>)/gi, "");
    const cleanTermsContents = termsContents.replace(/(<([^>]+)>)/gi, "");

    return cleanTermsName + cleanTermsContents;
  }, [termsList, selectedTab]);

  return (
    <>
      <THeader title={title} ariaLabel={$L("TERMS OF SERVICE, heading 1")} />
      <TBody cbScrollTo={cbScrollTo} className={css.tBody}>
        <div className={css.termsContainer}>
          <div className={classnames(css.contentsBox, { [css.optionalTabActive]: isOptionalTab })}>
            <TButtonTab
              contents={tabList}
              className={css.tTab}
              onItemClick={handleItemClick}
              selectedIndex={selectedTab && selectedTab}
            />
            <div className={css.scrollerWrapper}>
              {isOptionalTab ? (
                <div className={css.textBox} aria-label={termsAriaLabel}>
                  <div
                    className={css.text}
                    dangerouslySetInnerHTML={{
                      __html: termsList && termsList[selectedTab]?.termsContents,
                    }}
                  />
                </div>
              ) : (
                <TButtonScroller
                  boxHeight={scaleH(714)}
                  width={scaleW(1680)}
                  resetScrollPosition={resetScroll}
                >
                  <div className={css.textBox} aria-label={termsAriaLabel}>
                    <div
                      className={css.text}
                      dangerouslySetInnerHTML={{
                        __html: termsList && termsList[selectedTab]?.termsContents,
                      }}
                    />
                  </div>
                </TButtonScroller>
              )}
            </div>

            {termsList[selectedTab]?.trmsTpCd === "MST00405" ? (
              <div className={css.optionalContainer}>
                {/* <div className={css.checkboxContainer}>
                  <TCheckBoxSquare
                    selected={optionalTermsAgree || isOptionalChecked}
                    onToggle={handleOptionalCheckboxToggle}
                    spotlightId="optional-agree-checkbox"
                    spotlightDisabled={spotlightDisabled || optionalTermsAgree}
                    disabled={optionalTermsAgree}
                  />
                  <div
                    className={`${css.checkboxLabel} ${
                      optionalTermsAgree ? css.disabledLabel : ""
                    }`}
                  >
                    {$L(
                      "I agree to receive Personalized Recommendations and Advertisements"
                    )}
                  </div>
                </div> */}
                <div className={css.buttonContainer}>
                  <TButton
                    onClick={handleOptionalAgree}
                    className={css.agreeButton}
                    spotlightId="optional-agree-button"
                    spotlightDisabled={
                      spotlightDisabled || optionalTermsAgree
                    }
                    disabled={localOptionalTermsAgree}
                  >
                    {$L("Agree")}
                  </TButton>
                  <TButton
                    onClick={handleOptionalDisagree}
                    className={css.disagreeButton}
                    spotlightDisabled={spotlightDisabled || !optionalTermsAgree}
                    spotlightId="optional-disagree-button"
                    disabled={!localOptionalTermsAgree}
                  >
                    {$L("Do Not Agree")}
                  </TButton>
                </div>
              </div>
            ) : (
              <div className={css.buttonBox}>
                {empTermsData && (
                  <div className={css.termText}>
                    {termsList[selectedTab]?.termsId === "20211118044_US"
                      ? $L(
                          "You can change your agreement to the terms and conditions in your LG Account."
                        )
                      : termsList[selectedTab]?.termsId === "20230908001_US"
                        ? $L(
                            "If you do not wish to agree to these terms, please proceed to the following link."
                          )
                        : null}
                  </div>
                )}
                <TButton
                  spotlightDisabled={spotlightDisabled}
                  onClick={
                    termsList[selectedTab]?.trmsTpCd === "MST00401" ||
                    termsList[selectedTab]?.trmsTpCd === "MST00402"
                      ? handleDisagree
                      : handleLGAccount
                  }
                  type={TYPES.mypage}
                  className={css.locateBox}
                  ariaLabel={
                    termsList[selectedTab]?.trmsTpCd === "MST00401" ||
                    termsList[selectedTab]?.trmsTpCd === "MST00402"
                      ? $L("Do Not Agree")
                      : $L("LG Account")
                  }
                >
                  {termsList[selectedTab]?.trmsTpCd === "MST00401" ||
                  termsList[selectedTab]?.trmsTpCd === "MST00402"
                    ? $L("Do Not Agree")
                    : $L("LG Account")}
                </TButton>
              </div>
            )}
          </div>

          {/* TODO 추후 폰트 변경 */}
          <TPopUp
            kind="exitPopup"
            open={popupVisible}
            onExit={onExit}
            onClose={onClose}
            hasButton
            button1Text={$L("Yes")}
            button2Text={$L("No")}
            hasText
            title={$L("")}
            text={
              <div>
                {$L("Are you sure you want to opt out?")}
                <br />
                <p style={{ color: "black" }}>
                  {$L(
                    "The service will not be available anymore after opting out."
                  )}
                </p>
              </div>
            }
          />

          <TPopUp
            kind="exitPopup"
            open={closePopUp}
            hasText
            title={$L("")}
            text={$L(
              "Thank you for using the Shop Time, and we hope to see you again. The app will close in 3 seconds."
            )}
          />

          <TPopUp
            kind="exitPopup"
            open={agreePopup}
            onClose={() => setAgreePopup(false)}
            hasText
            title={$L("")}
            text={$L(
              "From now on, you can receive personalized shopping benefits."
            )}
          />

          {/* 새로 추가된 optionalAgreement 팝업 */}
          <TPopUp
            kind="exitPopup"
            open={optionalDisagreePopupOpen}
            onClose={() => setOptionalDisagreePopupOpen(false)}
            onExit={confirmOptionalDisagree}
            hasButton
            button1Text={$L("Yes")}
            button2Text={$L("No")}
            hasText
            title={$L("")}
            text={$L("You will not receive personalized shopping benefits")}
          />
          {/* 필수약관 체크 확인 팝업 */}
          <TPopUp
            kind="textPopup"
            open={showCheckboxAlert}
            onClose={() => setShowCheckboxAlert(false)}
            hasButton
            button1Text={$L("OK")}
            hasText
            title={$L("Notice")}
            text={$L("Please check the box to agree to the terms.")}
          />
        </div>
      </TBody>
    </>
  );
}

