// src/components/Optional/OptionalTermsConfirmTest.jsx

import React, { useEffect, useCallback, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import TPopUp from '../TPopUp/TPopUp';
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 './OptionalTermsConfirmTest.module.less';

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

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

  useEffect(() => {
    console.log("OptionalTermsTest - in Component Rendered");
  }, []);

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

  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);
  }, []);

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

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

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

      dispatch(setMyPageTermsAgree({ termsList, notTermsList }, callback));
      dispatch(setHidePopup());
    } else {
      setIsWarningPopupVisible(true);
    }
  }, [isChecked, dispatch]);
  
  const handleCloseWarningPopup = useCallback(() => {
    setIsWarningPopupVisible(false);
  }, []);

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

  if (isTermsPopupVisible) {
    return (
      <TPopUp
        kind="introTermsPopup"
        open
        onClose={handleCloseTermsPopup}
        onClick={handleCloseTermsPopup}
        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>
        )}
      </TPopUp>
    );
  }

  if (isWarningPopupVisible) {
    return (
      <TPopUp
        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 (
    <TPopUp
      kind="introTermsPopup"
      open={open}
      onClose={handleMainPopupClose}
      spotlightId="optional-terms-test-popup"
      className={css.testPopup}
      type="none"
      style={{
        position: 'absolute',
        top: '100px',
        left: '270px',
        zIndex: 9999
      }}
    >
      <div className={css.contentContainer}>
        <div className={css.mainContent}>
          <div className={css.checkboxSection}>
            <div className={css.checkboxArea}>
              <TCheckBoxSquare 
                selected={isChecked}
                onToggle={handleCheckboxToggle}
                spotlightId="optional-checkbox"
                className={css.checkbox}
              />
               <TButton
                className={css.termBox}
                onClick={handleViewTermsClick}
                spotlightId="optional-terms-button"
                type="terms"
                ariaLabel={$L("View Optional Terms")}
              >
                <div className={css.termTitle}>Optional Terms</div>                
              </TButton>
            </div>
          </div>
          
          <div className={css.descriptionSection}>
            <div className={css.description}>
              Get recommendations, special offers, and ads tailored just for you.
            </div>
          </div>
          
          <div className={css.buttonSection}>
            <div className={css.buttonGroup}>
              <TButton 
                onClick={handleAgree}
                spotlightId="agree-button"
                className={css.agreeButton}
              >
                {$L('Agree')}
              </TButton>
              <TButton 
                onClick={handleMainPopupClose}
                spotlightId="not-now-button"
                className={css.notNowButton}
              >
                {$L('Not Now')}
              </TButton>
              <TButton 
                onClick={handleDontAskAgain}
                spotlightId="dont-ask-button"
                className={css.dontAskButton}
              >
                {$L("Don't Ask Again")}
              </TButton>
            </div>
          </div>
        </div>
      </div>
    </TPopUp>
  );
};

export default OptionalTermsConfirmTest;