// src/views/MyPagePanel/MyPageSub/TermsOfService/TermsOfOptional.jsx

/**
 * ShopTime 애플리케이션의 선택적 약관 동의 컴포넌트 (IntroPanel 기반 단순화 버전)
 * 
 * @component TermsOfOptional
 * @description 
 * webOS TV 환경에서 선택적 약관 정보를 표시하고 사용자의 동의 여부를 관리합니다.
 * IntroPanel과 동일한 구조로 모달 문제 없이 안전하게 동작합니다.
 */
import React, { useCallback, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import Spotlight from "@enact/spotlight";

import {
  setHidePopup,
  setShowPopup,
  setExitApp
} from "../../../../actions/commonActions";
import { registerDevice } from "../../../../actions/deviceActions";
import { sendLogTerms } from "../../../../actions/logActions";
import { popPanel } from "../../../../actions/panelActions";

import TBody from "../../../../components/TBody/TBody";
import TPanel from "../../../../components/TPanel/TPanel";
import TButton from "../../../../components/TButton/TButton";
import TCheckBoxSquare from "../../../../components/TCheckBox/TCheckBoxSquare";
import TPopUp from "../../../../components/TPopUp/TPopUp";

import * as Config from "../../../../utils/Config";
import { $L } from "../../../../utils/helperMethods";
import css from "./TermsOfOptionalSimple.module.less";

// 약관 타입 정의
const TERMS_TYPE = {
  TERMS_CONDITIONS: 'TERMS_CONDITIONS',
  PRIVACY_POLICY: 'PRIVACY_POLICY', 
  OPTIONAL_TERMS: 'OPTIONAL_TERMS'
};

// 약관 ID 매핑
const TERMS_ID_MAP = {
  [TERMS_TYPE.TERMS_CONDITIONS]: "TID0000222",
  [TERMS_TYPE.PRIVACY_POLICY]: "TID0000223", 
  [TERMS_TYPE.OPTIONAL_TERMS]: "TID0000232"
};

// 약관 표시명
const TERMS_DISPLAY_NAMES = {
  [TERMS_TYPE.TERMS_CONDITIONS]: "이용약관 동의 (필수)",
  [TERMS_TYPE.PRIVACY_POLICY]: "개인정보처리방침 동의 (필수)",
  [TERMS_TYPE.OPTIONAL_TERMS]: "선택약관 동의"
};

// 필수 약관 여부 확인
const isMandatoryTerms = (type) => {
  return type === TERMS_TYPE.TERMS_CONDITIONS || type === TERMS_TYPE.PRIVACY_POLICY;
};

// 초기 체크박스 상태
const getInitialCheckboxStates = () => ({
  [TERMS_TYPE.TERMS_CONDITIONS]: false,
  [TERMS_TYPE.PRIVACY_POLICY]: false,
  [TERMS_TYPE.OPTIONAL_TERMS]: false
});

export default function TermsOfOptional({
  title,
  isModalMode,
  closeModalCallback,
  panelInfo,
  spotlightId = "termsOfOptionalPanel",
  initialAgreeState,
}) {
  const dispatch = useDispatch();
  
  // Redux state
  const commonPopupState = useSelector((state) => state.common?.popup || {});
  const { popupVisible = false, activePopup = null } = commonPopupState;
  const deviceState = useSelector((state) => state.device);

  // 컴포넌트 상태
  const [checkboxStates, setCheckboxStates] = useState(() => getInitialCheckboxStates());
  const [isAllChecked, setIsAllChecked] = useState(false);
  const [spotlightDisabled, setSpotlightDisabled] = useState(false);

  // 체크박스 개별 토글 핸들러
  const handleCheckboxToggle = useCallback((type) => ({ selected }) => {
    console.log(`[CHECKBOX-CLICK] ${type} 체크박스 클릭됨:`, selected);
    
    setCheckboxStates(prev => {
      const newStates = { ...prev, [type]: selected };
      const allChecked = Object.values(newStates).every(state => state);
      setIsAllChecked(allChecked);
      console.log(`[CHECKBOX-CLICK] 새로운 전체 상태:`, newStates);
      return newStates;
    });
  }, []);

  // 전체 선택 토글 핸들러
  const handleSelectAllToggle = useCallback(({ selected }) => {
    console.log(`[SELECT-ALL-CLICK] 전체 선택 클릭됨:`, selected);
    
    setIsAllChecked(selected);
    setCheckboxStates(prev => {
      const newStates = Object.keys(prev).reduce((acc, key) => ({
        ...acc,
        [key]: selected
      }), {});
      console.log(`[SELECT-ALL-CLICK] 새로운 전체 상태:`, newStates);
      return newStates;
    });
  }, []);

  // 약관 내용 보기 핸들러 (간단한 알림 팝업으로 대체)
  const handleTermsView = useCallback((type) => {
    const termName = TERMS_DISPLAY_NAMES[type];
    const termId = TERMS_ID_MAP[type];
    
    dispatch(setShowPopup(Config.ACTIVE_POPUP.alertPopup, {
      title: termName,
      text: `${termName}\n\n약관 ID: ${termId}\n\n실제 약관 내용은 서버에서 로드됩니다.\n현재는 단순화된 버전입니다.`,
      button1Text: $L("확인")
    }));
  }, [dispatch]);

  // 팝업 닫기 핸들러
  const handleClosePopup = useCallback(() => {
    console.log('[TermsOfOptional] handleClosePopup triggered');
    dispatch(setHidePopup());
  }, [dispatch]);

  // 앱 종료 핸들러
  const onExit = useCallback(() => {
    console.log('[TermsOfOptional] onExit triggered');
    dispatch(setHidePopup());
    dispatch(setExitApp());
  }, [dispatch]);

  // 팝업 취소 핸들러
  const onClose = useCallback(() => {
    console.log('[TermsOfOptional] onClose triggered');
    dispatch(setHidePopup());
  }, [dispatch]);

  // 뒤로가기 핸들러
  const handleBack = useCallback(() => {
    if (isModalMode && closeModalCallback) {
      console.log('[TermsOfOptional] Modal mode back pressed');
      closeModalCallback();
    } else if (!isModalMode && panelInfo && panelInfo.name) {
      console.log('[TermsOfOptional] Panel mode back pressed');
      dispatch(popPanel(panelInfo.name));
    } else {
      console.log('[TermsOfOptional] Back pressed - showing exit popup');
      dispatch(setShowPopup(Config.ACTIVE_POPUP.exitPopup));
    }
  }, [isModalMode, closeModalCallback, dispatch, panelInfo]);

  // 동의 버튼 핸들러
  const handleAgree = useCallback(() => {
    // 필수 약관 검증
    const hasRequiredTerms = checkboxStates[TERMS_TYPE.TERMS_CONDITIONS] && 
                            checkboxStates[TERMS_TYPE.PRIVACY_POLICY];
    
    if (!hasRequiredTerms) {
      dispatch(setShowPopup(Config.ACTIVE_POPUP.alertPopup, {
        title: $L("Notice"),
        text: $L("Please agree to all required terms."),
        button1Text: $L("OK")
      }));
      return;
    }

    // 동의한 약관 ID 배열 구성
    const agreeTerms = [];
    if (checkboxStates[TERMS_TYPE.TERMS_CONDITIONS]) {
      agreeTerms.push(TERMS_ID_MAP[TERMS_TYPE.TERMS_CONDITIONS]);
    }
    if (checkboxStates[TERMS_TYPE.PRIVACY_POLICY]) {
      agreeTerms.push(TERMS_ID_MAP[TERMS_TYPE.PRIVACY_POLICY]);
    }
    if (checkboxStates[TERMS_TYPE.OPTIONAL_TERMS]) {
      agreeTerms.push(TERMS_ID_MAP[TERMS_TYPE.OPTIONAL_TERMS]);
    }

    console.log('최종 전송될 agreeTerms:', agreeTerms);

    // registerDevice 호출
    dispatch(registerDevice({ agreeTerms }));
  }, [checkboxStates, dispatch]);

  // registerDevice 성공 감지
  useEffect(() => {
    console.log('📊 deviceState 변화 감지:', deviceState);
    
    if (deviceState?.regDeviceData && 
        (deviceState.regDeviceData.retCode === 0 || deviceState.regDeviceData.retCode === "000")) {
      console.log('✅ registerDevice 성공 감지');
      
      setTimeout(() => {
        if (isModalMode && closeModalCallback) {
          console.log('📱 Modal mode - closeModalCallback 호출');
          closeModalCallback(true);
        } else {
          console.log('📋 Panel mode - popPanel 호출');
          dispatch(popPanel());
        }
      }, 1000);
    }
  }, [deviceState, isModalMode, closeModalCallback, dispatch]);

  // 비동의 버튼 핸들러
  const handleDoNotAgree = useCallback(() => {
    console.log('[TermsOfOptional] Do Not Agree pressed');
    
    dispatch(sendLogTerms({ logTpNo: Config.LOG_TP_NO.TERMS.DO_NOT_AGREE }));
    
    dispatch(setShowPopup(Config.ACTIVE_POPUP.exitPopup, {
      title: $L(""),
      text: (
        <div>
          {$L("Are you sure you want to opt out?")}
          <br />
          <p style={{ color: "black", fontWeight: "bold" }}>
            {$L("The service will not be available anymore after opting out.")}
          </p>
        </div>
      ),
      button1Text: $L("Yes"),
      button2Text: $L("No"),
      onButton1Press: onExit,
      onButton2Press: onClose
    }));
  }, [dispatch, onExit, onClose]);

  // 컴포넌트 마운트 시 포커스 설정
  useEffect(() => {
    setSpotlightDisabled(false);
    
    const timer = setTimeout(() => {
      Spotlight.set('checkbox-all');
    }, 200);
    
    return () => clearTimeout(timer);
  }, []);

  // Exit Popup 포커스 관리
  useEffect(() => {
    if (activePopup === Config.ACTIVE_POPUP.exitPopup && popupVisible) {
      const timer = setTimeout(() => {
        const focusAttempts = [
          () => Spotlight.set('tPopupBtn2'),
          () => Spotlight.set('tPopupBtn1'),
        ];
        
        for (const attempt of focusAttempts) {
          if (attempt()) {
            console.log('포커스 설정 성공');
            break;
          }
        }
      }, 300);

      return () => clearTimeout(timer);
    }
  }, [activePopup, popupVisible]);

  return (
    <TPanel
      title={title || $L("Terms and Conditions")}
      handleCancel={handleBack}
      className={css.panel}
      spotlightId={spotlightId}
      noCloseButton={isModalMode}
    >
      <TBody className={css.introLayout}>
        {/* Welcome Section */}
        <div className={css.title}>
          <span className={css.welcomeText}>{$L("Welcome to")}</span>
          <span className={css.txtPoint}>
            <span className={css.brandShop}>Sh</span>
            <span className={css.pointColor}>o</span>
            <span className={css.brandPTime}>p Time !</span>
          </span>
        </div>
        
        <div className={css.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.")}
        </div>

        {/* Terms Section */}
        <div className={css.termsItemsLayer}>
          {Object.entries(TERMS_TYPE).map(([key, type]) => (
            <div key={type} className={css.termItem}>
              <TCheckBoxSquare 
                id={`checkbox-${type.toLowerCase()}`}
                data-spotlight-id={`checkbox-${type.toLowerCase()}`}
                selected={checkboxStates[type]}
                onToggle={handleCheckboxToggle(type)}
                className={css.termCheckbox}
                disabled={spotlightDisabled}
                spotlightDisabled={spotlightDisabled}
                tabIndex={2}
                aria-label={TERMS_DISPLAY_NAMES[type]}
                role="checkbox"
                aria-checked={checkboxStates[type]}
              />
              <div className={css.termsButton}>
                <TButton
                  data-spotlight-id={`termbox-${type.toLowerCase()}`}
                  onClick={() => handleTermsView(type)}
                  className={css.termBox}
                  spotlightDisabled={spotlightDisabled}
                >
                  <span className={`${css.termName} ${isMandatoryTerms(type) ? css.termNameMandatory : ''}`}>
                    {TERMS_DISPLAY_NAMES[type]}
                  </span>
                  <div className={css.expandIconContainer}>
                    <svg width="37" height="37" viewBox="0 0 37 37" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <rect x="2.5" y="2.5" width="32" height="32" rx="16" stroke="black" strokeWidth="2.5"/>
                      <path d="M16.0059 25.8301L22.74 19.1108C22.8205 19.0307 22.8844 18.9355 22.928 18.8306C22.9716 18.7258 22.994 18.6133 22.994 18.4998C22.994 18.3862 22.9716 18.2738 22.928 18.1689C22.8844 18.0641 22.8205 17.9689 22.74 17.8888L16.0059 11.1701" stroke="black" strokeWidth="2.5" strokeLinecap="round"/>
                    </svg>
                  </div>
                </TButton>
              </div>
            </div>
          ))}
        </div>

        {/* Select All Section */}
        <div className={css.selectAllSection}>
          <TCheckBoxSquare 
            id="checkbox-all"
            data-spotlight-id="checkbox-all"
            selected={isAllChecked}
            onToggle={handleSelectAllToggle}
            className={css.selectAllCheckbox}
            disabled={spotlightDisabled}
            spotlightDisabled={spotlightDisabled}
            tabIndex={1}
          />
          <span className={css.selectAllText}>{$L("Select All")}</span>
        </div>

        {/* Bottom Button Layer */}
        <div className={css.bottomBtnLayer}>
          <TButton
            onClick={handleAgree}
            className={css.agreeButton}
            spotlightId={spotlightId + "_agreeButton"}
          >
            {$L("Agree")}
          </TButton>
          
          <TButton 
            onClick={handleDoNotAgree} 
            className={css.disagreeButton}
            spotlightId={spotlightId + "_disagreeButton"}
          >
            {$L("Do Not Agree")}
          </TButton>
        </div>

        {/* Alert Popup */}
        {activePopup === Config.ACTIVE_POPUP.alertPopup && popupVisible && (
          <TPopUp
            kind="alertPopup"
            open={popupVisible}
            onClose={handleClosePopup}
            onButton1Press={handleClosePopup}
            hasButton
            button1Text={commonPopupState.button1Text || $L("OK")}
            hasText
            title={commonPopupState.title}
            text={commonPopupState.text}
          />
        )}

        {/* Exit Popup */}
        {activePopup === Config.ACTIVE_POPUP.exitPopup && popupVisible && (
          <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", fontWeight: "bold" }}>
                  {$L("The service will not be available anymore after opting out.")}
                </p>
              </div>
            }
          />
        )}
      </TBody>
    </TPanel>
  );
}