// src/components/Optional/OptionalTermsConfirm.jsx

import React, { useEffect, useCallback, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import TNewPopUp from '../TPopUp/TNewPopUp';
import TButton from '../TButton/TButton';
import TCheckBoxSquare from '../TCheckBox/TCheckBoxSquare';
import TButtonScroller from '../TButtonScroller/TButtonScroller';
import { $L, scaleH, scaleW } from '../../utils/helperMethods';
import { setHidePopup } from '../../actions/commonActions';
import { setMyPageTermsAgree } from '../../actions/myPageActions';
import css from './OptionalTermsConfirmBottom.module.less';
import cssPopup from '../TPopUp/TNewPopUp.module.less';
import Spotlight from "@enact/spotlight";

const OptionalTermsConfirm = ({ open }) => {
  const dispatch = useDispatch();

  const [isChecked, setIsChecked] = useState(false);
  const [isTermsPopupVisible, setIsTermsPopupVisible] = useState(false);
  const [isWarningPopupVisible, setIsWarningPopupVisible] = useState(false);
 

  const optionalTermsData = useSelector((state) => 
    state.home.termsData?.data?.terms.find(term => term.trmsTpCd === "MST00405")
  );


  // 포커스 복원을 위한 useEffect 추가
  useEffect(() => {
    if (open && !isTermsPopupVisible && !isWarningPopupVisible) {
      const timer = setTimeout(() => {
        Spotlight.focus("optional-terms-confirm-popup");
      }, 150); // 약간 더 긴 지연

      return () => clearTimeout(timer);
    }
  }, [open, isTermsPopupVisible, isWarningPopupVisible]);

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

  const handleCheckboxToggle = useCallback(({ selected }) => {
    setIsChecked(selected);
  }, []);

  const handleViewTermsClick = useCallback(() => {
    setIsTermsPopupVisible(true);
  }, []);

  const handleCloseTermsPopup = useCallback((e) => {
    if (e) {
      e.stopPropagation();
    }
    setIsTermsPopupVisible(false);
    Spotlight.focus("optional-terms-confirm-popup");
  }, []);

  const handleTermsPopupClosed = useCallback(() => {
    setTimeout(() => {
      Spotlight.focus("optional-terms-confirm-popup");
    }, 50);
  }, []);

  const handleAgreeTest = useCallback(() => {
    console.log("handleAgreeTest");
    Spotlight.pause();
    setIsTermsPopupVisible(false);    
    // 상태 업데이트 후 DOM이 완전히 렌더링될 때까지 기다린 후 포커스
    setTimeout(() => {
      Spotlight.resume();
      Spotlight.focus("optional-terms-confirm-popup");
    }, 500); // 50ms에서 100ms로 증가
    
  }, []);

  const handleAgree = useCallback(() => {
    if (isChecked) {
      // 약관 동의할 항목들 (string array)
      const termsList = ["TID0000222", "TID0000223", "TID0000232"];
    
      // 동의하지 않을 항목들 (빈 배열)
      const notTermsList = [];

      console.log('OptionalTermsConfirm -약관 동의 API 호출 파라미터:', { termsList, notTermsList });

      const callback = (response) => {
        if (response.retCode === "000" || response.retCode === 0) {
          console.log('약관 동의 성공:', response);
        } else {
          console.error('약관 동의 실패:', response);
        }
      };

      console.log('OptionalTermsConfirm - 약관 동의 API 호출 payload:', { termsList, notTermsList });
      dispatch(setMyPageTermsAgree({ termsList, notTermsList }, callback));
      dispatch(setHidePopup());
    } else {
      setIsWarningPopupVisible(true);
    }
  }, [isChecked, dispatch]);
  
  const handleCloseWarningPopup = useCallback(() => {
    setIsWarningPopupVisible(false);
    Spotlight.focus("optional-terms-confirm-popup");
  }, []);

  const handleDontAskAgain = () => {
    console.log("Don't Ask Again 처리 필요");
    dispatch(setHidePopup());
  };

  if (isTermsPopupVisible) {
    return (
      <TNewPopUp
        kind="introTermsPopup"
        open
        onClose={handleTermsPopupClosed}
        onClick={handleCloseTermsPopup}
        onIntroTermsAgreeClick={handleAgreeTest}
        hasButton
        button1Text={$L("OK")}
        spotlightId="terms-viewer-popup"
      >
        {optionalTermsData && (
          <div className={css.termsViewerContent}>
            <div className={css.termsViewerTitle}>{$L("Optional Terms")}</div>
            <TButtonScroller
              boxHeight={scaleH(300)}
              width={scaleW(980)}
              className={css.termsDescription}
            >
              <div
                className={css.termsDesc}
                dangerouslySetInnerHTML={{
                  __html: optionalTermsData.trmsCntt,
                }}
              />
            </TButtonScroller>
          </div>
        )}
      </TNewPopUp>
    );
  }

  if (isWarningPopupVisible) {
    return (
      <TNewPopUp
        kind="textPopup"
        open
        onClose={handleCloseWarningPopup}
        hasButton
        button1Text={$L("OK")}
        hasText
        title={$L("Agreement Required")}
        text={$L("Please agree to the Optional Terms.")}
        spotlightId="warning-popup"
      />
    );
  }

  return (
    <TNewPopUp
      kind="optionalConfirm"
      open={open}      
      spotlightId="optional-terms-confirm-popup"
      spotlightRestrict="self-only"
      className={css.optionalConfirmPopup}
      onOptionalTermsClick={handleViewTermsClick}
      onOptionalAgreeClick={handleAgree}
      onOptionalDeclineClick={handleDontAskAgain}
      customPosition={true} 
      position={{
        position: 'absolute',
        top: '342px',  // 가운데를 기준으로 한 좌표 (1080/2) - 198
        left: '0px',
        bottom: 'unset',
        transform: 'none',
      }}
    />
  );
};

export default OptionalTermsConfirm;