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

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

import Alert from "@enact/sandstone/Alert";
import Spotlight from "@enact/spotlight";
import SpotlightContainerDecorator from "@enact/spotlight/SpotlightContainerDecorator";
import Spottable from "@enact/spotlight/Spottable";

import defaultImageItem from "../../../assets/images/img-thumb-empty-product@3x.png";
import { cancelFocusElement, focusElement } from "../../actions/commonActions";
import { SpotlightIds } from "../../utils/SpotlightIds";
import CustomImage from "../CustomImage/CustomImage";
import TButton from "../TButton/TButton";
import TButtonScroller from "../TButtonScroller/TButtonScroller";
import css from "./TNewPopUp.module.less";
import { $L } from "../../utils/helperMethods";

const Container = SpotlightContainerDecorator(
  { enterTo: "default-element" },
  Spottable("div")
);

const OptionContainer = SpotlightContainerDecorator(
  { enterTo: "last-focused" },
  Spottable("ul")
);

const ButtonContainer = SpotlightContainerDecorator("div");
const ButtonContainerNegative = SpotlightContainerDecorator(
  { defaultElement: `[data-spotlight-id="${"tPopupBtn2"}"]` },
  "div"
);
const IntroTermsButtonContainer = SpotlightContainerDecorator(
  { defaultElement: '[data-spotlight-id="introTermsAgreeBtn"]' },
  "div"
);
const OptionalConfirmButtonSection = SpotlightContainerDecorator(
  { defaultElement: '[data-spotlight-id="optionalConfirmAgreeBtn"]' },
  "div"
);
const SpottableComponent = Spottable("li");
const SpottableDiv = Spottable("div");

const KINDS = [
  "textPopup",
  "termsPopup",
  "introTermsPopup",
  "optionPopup",
  "eventBannerPopup",
  "supportPopup",
  "exitPopup",
  "couponPopup",
  "mobileSendPopup",
  "qrPopup",
  "checkoutTermsPopup",
  "scrollPopup",
  "watchPopup",
  "setPinCodePopup",
  "descriptionPopup",
  "errorPopup",
  "orderDetailPopup",
  "returnExchangePopup",
  "orderCancelPopup",
  "cancelConfirmPopup",
  "trackPackagePopup",
  "optionalAgreement",
  "normal",
  "optionalConfirm",
  "figmaTermsPopup",
];

// 각 kind별 클래스명 매핑
const CLASS_MAPPINGS = {
  introTermsPopup: {
    info: "introTermsInfo",
    textLayer: "commonTextLayer",
    title: "commonTitle",
    text: "commonText",
    buttonContainer: "introTermsButtonContainer"
  },
  descriptionPopup: {
    info: "descriptionInfo",
    textLayer: "commonTextLayer",
    title: "commonTitle",
    text: "commonText",
    buttonContainer: "descriptionButtonContainer",
    img: "descriptionImg"
  },
  textPopup: {
    info: "textExitInfo",
    textLayer: "commonTextLayer",
    title: "commonTitle",
    text: "textExitText",
    buttonContainer: "textExitButtonContainer"
  },
  exitPopup: {
    info: "textExitInfo",
    textLayer: "commonTextLayer",
    title: "commonTitle",
    text: "textExitText",
    buttonContainer: "textExitButtonContainer"
  },
  optionPopup: {
    info: "optionInfo",
    textLayer: "commonTextLayer",
    title: "commonTitle",
    text: "commonText",
    buttonContainer: "optionButtonContainer",
    optionLayer: "optionLayer",
    option: "optionChoice",
    img: "optionImg"
  },
  eventBannerPopup: {
    info: "eventBannerInfo",
    textLayer: "commonTextLayer",
    title: "commonTitle",
    text: "commonText",
    buttonContainer: "eventBannerButtonContainer"
  },
  supportPopup: {
    info: "supportInfo",
    textLayer: "commonTextLayer",
    title: "commonTitle",
    text: "commonText",
    buttonContainer: "supportButtonContainer"
  },
  couponPopup: {
    info: "couponInfo",
    textLayer: "commonTextLayer",
    title: "commonTitle",
    text: "commonText",
    buttonContainer: "couponButtonContainer"
  },
  mobileSendPopup: {
    info: "mobileSendInfo",
    textLayer: "commonTextLayer",
    title: "commonTitle",
    text: "commonText",
    buttonContainer: "mobileSendButtonContainer"
  },
  qrPopup: {
    info: "qrInfo",
    textLayer: "commonTextLayer",
    title: "commonTitle",
    text: "commonText",
    buttonContainer: "qrButtonContainer"
  },
  checkoutTermsPopup: {
    info: "checkoutTermsInfo",
    textLayer: "commonTextLayer",
    title: "checkoutTermsTitle",
    text: "checkoutTermsText",
    buttonContainer: "checkoutTermsButtonContainer"
  },
  scrollPopup: {
    info: "scrollInfo",
    textLayer: "commonTextLayer",
    title: "commonTitle",
    text: "commonText",
    buttonContainer: "scrollButtonContainer"
  },
  watchPopup: {
    info: "watchInfo",
    textLayer: "watchTextLayer",
    title: "watchTitle",
    text: "watchText",
    buttonContainer: "watchButtonContainer",
    thumbnail: "watchThumbnail"
  },
  setPinCodePopup: {
    info: "setPinCodeInfo",
    textLayer: "commonTextLayer",
    title: "commonTitle",
    text: "setPinCodeText",
    buttonContainer: "setPinCodeButtonContainer"
  },
  errorPopup: {
    info: "errorInfo",
    textLayer: "commonTextLayer",
    title: "commonTitle",
    text: "errorText",
    buttonContainer: "errorButtonContainer"
  },
  orderCancelPopup: {
    info: "orderCancelInfo",
    textLayer: "commonTextLayer",
    title: "commonTitle",
    text: "orderCancelText",
    buttonContainer: "orderCancelButtonContainer"
  },
  returnExchangePopup: {
    info: "returnExchangeInfo",
    textLayer: "commonTextLayer",
    title: "commonTitle",
    text: "returnExchangeText",
    buttonContainer: "returnExchangeButtonContainer"
  },
  trackPackagePopup: {
    info: "trackPackageInfo",
    textLayer: "commonTextLayer",
    title: "commonTitle",
    text: "trackPackageText",
    buttonContainer: "trackPackageButtonContainer"
  },
  cancelConfirmPopup: {
    info: "cancelConfirmInfo",
    textLayer: "commonTextLayer",
    title: "commonTitle",
    text: "cancelConfirmText",
    buttonContainer: "cancelConfirmButtonContainer"
  },
  optionalAgreement: {
    info: "optionalAgreementInfo",
    textLayer: "optionalAgreementTextLayer",
    title: "commonTitle",
    text: "optionalAgreementText",
    buttonContainer: "optionalAgreementButtonContainer",
    contentContainer: "optionalAgreementContentContainer"
  },
  optionalConfirm: {
    info: "optionalConfirmInfo",
    textLayer: "optionalConfirmTextLayer",
    title: "optionalConfirmTitle",
    text: "optionalConfirmText",
    buttonContainer: "optionalConfirmButtonContainer",
    contentContainer: "optionalConfirmContentContainer"  // 👈 추가
  },
  figmaTermsPopup: {
    info: "figmaTermsInfo",
    contentContainer: "figmaTermsContentContainer",
    termsCard: "figmaTermsCard",
    titleBar: "figmaTermsTitleBar",
    titleText: "figmaTermsTitleText",
    contentBody: "figmaTermsContentBody",
    buttonContainer: "figmaTermsButtonContainer",
    agreeButton: "figmaTermsAgreeButton",
    closeButton: "figmaTermsCloseButton"
  }
};

// 기본값 설정
const getClassName = (kind, element) => {
  const mapping = CLASS_MAPPINGS[kind];
  if (mapping && mapping[element]) {
    return css[mapping[element]];
  }
  // 기본값 반환 (기존 클래스명)
  return css[element];
};

export default function TNewPopUp({
  kind,
  children,
  onExit,
  onClick,
  currentPage,
  onRightClick,
  onLeftClick,
  itemLength,
  onClose,
  hasButton,
  hasText,
  hasOnClose = false,
  hasIndicator,
  hasLogo,
  hasThumbnail,
  thumbnail,
  logo,
  className,
  button1Text,
  button2Text,
  open,
  title,
  text,
  type = "overlay",
  options,
  optionClick,
  selectedIndex,
  spotlightId,
  onSpotlightRight,
  customPosition = false,
  position = {},
  onOptionalTermsClick,    // Optional Terms 버튼용
  onOptionalAgreeClick,    // Agree 버튼용
  onOptionalDeclineClick,  // Not Now 버튼용
  onIntroTermsAgreeClick,    // introTerms Agree 버튼용
  showAgreeButton = false,
  onAgreeClick, // onIntroTermsAgreeClick을 대체할 새로운 prop
  ...rest
}) {
  const dispatch = useDispatch();
  const popupVisible = useSelector((state) => state.common.popup.popupVisible);
  const httpHeader = useSelector((state) => state.common.httpHeader);

  useEffect(() => {
    if (popupVisible) {
      if (spotlightId) {
        const timerId = setTimeout(() => {
          Spotlight.focus(spotlightId);
        }, 0);

        return () => {
          clearTimeout(timerId);
        };
      }
      const timerId = setTimeout(() => {
        console.log("focusTarget = ", SpotlightIds.TPOPUP);
        Spotlight.focus(SpotlightIds.TPOPUP);
      }, 0);

      return () => {
        clearTimeout(timerId);
      };
    }
  }, [spotlightId, popupVisible]);

  useEffect(() => {
    if (KINDS.indexOf(kind) < 0) {
      console.error("TNewPopUp kind error");
    }
  }, [kind]);

  useEffect(() => {
    if (open) {
      let focusTarget = SpotlightIds.TPOPUP;
      if (kind === 'introTermsPopup') {
        focusTarget = 'introTermsAgreeBtn';
      } else if (kind === 'optionalConfirm') {
        focusTarget = 'optionalConfirmAgreeBtn';
      } else if (kind === 'figmaTermsPopup') {
        focusTarget = 'figma-terms-close';
      } else if (spotlightId) {
        focusTarget = spotlightId;
      }

      const timerId = setTimeout(() => {
        console.log("focusTarget is ", focusTarget);
        Spotlight.focus(focusTarget);
      }, 0);

      return () => {
        clearTimeout(timerId);
      };
    }
  }, [kind, open, spotlightId]);

  // useEffect(() => {
  //   if (open) {
  //     const focusTarget = spotlightId || SpotlightIds.TPOPUP;
  //     const timerId = setTimeout(() => {
  //       Spotlight.focus(focusTarget);
  //     }, 0);

  //     return () => {
  //       clearTimeout(timerId);
  //     };
  //   }
  // }, [open, spotlightId]);

  // 커스텀 스타일 생성
  const customStyle = useMemo(() => {
    if (!customPosition) return {};

    return {
      position: position.position || 'fixed',
      top: position.top,
      bottom: position.bottom,
      left: position.left,
      right: position.right,
      transform: position.transform,
      zIndex: position.zIndex || 99999,
      ...position.style // 추가 스타일
    };
  }, [customPosition, position]);

  const ButtonContainerComp = useMemo(() => {
    if (kind === "exitPopup") {
      return ButtonContainerNegative;
    }
    if (kind === "introTermsPopup") {
      return IntroTermsButtonContainer;
    }
    if (kind === "optionalConfirm") {
      return OptionalConfirmButtonSection;
    }
    return ButtonContainer;
  }, [kind]);

  // optionalAgreement
  // 자동으로 Yes/No 버튼 텍스트 설정


  const finalButton2Text = useMemo(() => {
    if (kind === "optionalAgreement" && !button2Text) {
      return $L("No");
    }
    return button2Text;
  }, [kind, button2Text]);

  // optionalAgreement일 경우 항상 버튼 표시
  const shouldShowButtons = useMemo(() => {
    return hasButton || kind === "optionalAgreement";
  }, [hasButton, kind]);


  const finalButton1Text = useMemo(() => {
    if (kind === "optionalAgreement" && !button1Text) {
      return $L("Yes");
    }
    if (kind === "introTermsPopup" && !button1Text) {
      return $L("Close");  // 기존 버튼을 Close로 변경
    }
    return button1Text;
  }, [kind, button1Text]);


  //-------------------------------------------------------

  const _onClick = useCallback(
    (e) => {
      if (onClick) {
        onClick(e);
      } else if (kind === "exitPopup") _onExit();
      else _onClose();
    },
    [kind, onClick, _onClose, _onExit]
  );

  const _onClose = useCallback(() => {
    if (onClose) {
      onClose();
    }
  }, [onClose]);

  const _onExit = useCallback(() => {
    if (onExit) {
      onExit();
    }
  }, [onExit]);

  const _onRightClick = useCallback(() => {
    if (onRightClick) {
      onRightClick();
    }
  }, [onRightClick]);

  const _onLeftClick = useCallback(() => {
    if (onLeftClick) {
      onLeftClick();
    }
  }, [onLeftClick]);

  const selectedOptClick = useCallback(
    (index, stock) => () => {
      if (stock > 0) {
        optionClick(index);
      }
    },
    [optionClick]
  );

  // 핸들러 함수들 추가
  const _onOptionalTermsClick = useCallback(() => {
    if (onOptionalTermsClick) {
      onOptionalTermsClick();
    }
  }, [onOptionalTermsClick]);

  const _onOptionalAgreeClick = useCallback(() => {
    if (onOptionalAgreeClick) {
      onOptionalAgreeClick();
    }
  }, [onOptionalAgreeClick]);

  const _onOptionalDeclineClick = useCallback(() => {
    if (onOptionalDeclineClick) {
      onOptionalDeclineClick();
    }
  }, [onOptionalDeclineClick]);

  const _onIntroTermsAgreeClick = useCallback(() => {
    if (onIntroTermsAgreeClick) {
      onIntroTermsAgreeClick();
    }
  }, [onIntroTermsAgreeClick]);

  const _onSpotlightRight = useCallback(
    (e) => {
      if (onSpotlightRight) onSpotlightRight(e);
    },
    [onSpotlightRight]
  );
  const alertStyle = useMemo(() => {
    if (kind === 'optionalConfirm') {
      return {
        bottom: 'unset',
        transform: 'none'
      };
    }
    return {};
  }, [kind]);

  if (!open) {
    return null;
  }



  return (
    <Alert
      {...rest}
      type={type}
      open={open}
      className={classNames(css.tNewPopUp, css[kind], className)}
      onClose={onClose}
      style={alertStyle}
    >
      <Container
        className={getClassName(kind, "info")}
        spotlightId={SpotlightIds.TPOPUP}
        spotlightDisabled={rest.spotlightDisabled}
        style={customPosition ? customStyle : undefined} // 👈 커스텀 스타일 적용
      >
        {hasOnClose && (
          <TButton
            className={css.closeBtn}
            onClick={_onClose}
            aria-label={$L("Close")}
            role="button"
          ></TButton>
        )}
        {hasThumbnail && (
          <div className={getClassName(kind, "thumbnail")}>
            <CustomImage
              src={thumbnail}
              fallbackSrc={defaultImageItem}
              alt="thumbnail"
            />
          </div>
        )}
        {hasText && (
          <div className={getClassName(kind, "textLayer")}>
            {title && (
              <div className={getClassName(kind, "title")} aria-label={title + "heading 1"}>
                {title}
              </div>
            )}
            {hasLogo && logo !== null && (
              <span>
                <CustomImage
                  src={logo}
                  fallbackSrc={defaultImageItem}
                  alt="logo"
                />
              </span>
            )}
            {text && (
              <div className={getClassName(kind, "text")} aria-label={text}>
                {text}
              </div>
            )}
          </div>
        )}
        {options && (
          <OptionContainer
            className={classNames(
              getClassName(kind, "optionLayer"),
              options.length >= 5 ? css.optionScroll : null
            )}
          >
            {options.map((option, index) => {
              const { prodOptCval, optImgUrl, optPrc, optStkQty, optNm } =
                option;
              const optStock = Number(optStkQty);

              return (
                <SpottableComponent
                  {...rest}
                  className={classNames(
                    getClassName(kind, "option"),
                    optStkQty > 0 &&
                      index === selectedIndex &&
                      css.selectedOption,

                    index == selectedIndex && css.focused,
                    optStkQty <= 0 && css.optionSoldOut
                  )}
                  spotlightId={`selectedOptionBtn-${index}`}
                  onClick={selectedOptClick(index, optStkQty)}
                  key={`option: ${index}`}
                  aria-label={optNm ? optNm : prodOptCval}
                  spotlightDisabled={optStkQty && optStkQty <= 0}
                >
                  {optImgUrl && (
                    <CustomImage
                      src={optImgUrl}
                      className={getClassName(kind, "img")}
                      fallbackSrc={defaultImageItem}
                      alt="optionImg"
                    />
                  )}
                  <div className={css.optionItem}>
                    <span>{optNm ? optNm : prodOptCval}</span>
                    {optStkQty && optStkQty <= 0 && (
                      <span>{$L("SOLD OUT")}</span>
                    )}
                  </div>

                  {optPrc && optStock !== 0 && `($${optPrc})`}
                </SpottableComponent>
              );
            })}
          </OptionContainer>
        )}

        {/* optionalAgreement의 특별한 구조 처리 */}
        {kind === "optionalAgreement" && (
          <div className={getClassName(kind, "contentContainer")}>
            {children}
          </div>
        )}



        {/* 다른 종류들의 children */}
        {kind !== "optionalAgreement" && kind !== "optionalConfirm" && kind !== "figmaTermsPopup" && children}

        {hasIndicator && (
          <>
            {currentPage !== 0 && (
              <SpottableDiv
                className={css.leftBtn}
                onClick={_onLeftClick}
                aria-label={$L("Back")}
                role="button"
              ></SpottableDiv>
            )}
            {currentPage !== itemLength - 1 && (
              <SpottableDiv
                className={css.rightBtn}
                onClick={_onRightClick}
                aria-label={$L("Next")}
                role="button"
              ></SpottableDiv>
            )}
          </>
        )}
        {shouldShowButtons && (
          <ButtonContainerComp className={getClassName(kind, "buttonContainer")}>
            {/* introTermsPopup일 때 Agree 버튼 먼저 표시 */}
            {kind === "introTermsPopup" && (
              <TButton
                spotlightId="introTermsAgreeBtn"
                onClick={_onIntroTermsAgreeClick}
                role="button"
                ariaLabel={$L("Agree")}
              >
                {$L("Agree")}
              </TButton>
            )}
            {finalButton1Text && (
              <TButton
                spotlightId="tPopupBtn1"
                onClick={_onClick}
                role="button"
                ariaLabel={finalButton1Text}
                onSpotlightRight={_onSpotlightRight}
              >
                {finalButton1Text}
              </TButton>
            )}
            {finalButton2Text && (
              <TButton
                spotlightId="tPopupBtn2"
                onClick={onClose}
                role="button"
                ariaLabel={finalButton2Text}
              >
                {finalButton2Text}
              </TButton>
            )}
          </ButtonContainerComp>
        )}

        {kind === "optionalConfirm" && (
          <div className={getClassName(kind, "optionalConfirmContentContainer")}>
            <div className={getClassName(kind, "optionalConfirmTextSection")}>
              {$L("Get recommendations, special offers, and ads tailored just for you.")}
            </div>
            <OptionalConfirmButtonSection className={getClassName(kind, "optionalConfirmButtonSection")}>
              <div className={getClassName(kind, "optionalConfirmLeftButtonSection")}>
                <TButton
                  className={css.optionalTermsButton}
                  onClick={_onOptionalTermsClick}
                  spotlightId="optionalConfirmTermsBtn"
                  type="terms"
                  ariaLabel={$L("Optional Terms")}
                  size="small"
                >
                  <div className={css.optionalTermsTitle}>{$L("Optional Terms")}</div>
                </TButton>
              </div>
              <div className={getClassName(kind, "optionalConfirmRightButtonSection")}>
                <TButton
                  className={getClassName(kind, "optionalConfirmButton")}
                  onClick={_onOptionalAgreeClick}
                  role="button"
                  ariaLabel={$L("Agree")}
                  spotlightId="optionalConfirmAgreeBtn"
                  size="small"
                >
                  {$L("Agree")}
                </TButton>
                <TButton
                  className={getClassName(kind, "optionalConfirmButton")}
                  onClick={_onOptionalDeclineClick}
                  role="button"
                  ariaLabel={$L("Not Now")}
                  spotlightId="optionalConfirmDeclineBtn"
                  size="small"
                >
                  {$L("Not Now")}
                </TButton>

              </div>
            </OptionalConfirmButtonSection>
          </div>
        )}

        {/* [추가] figmaTermsPopup을 위한 전용 렌더링 블록 */}
        {kind === "figmaTermsPopup" && (
          <div className={getClassName(kind, "contentContainer")}>
            <div className={getClassName(kind, "termsCard")}>
              <div className={getClassName(kind, "titleBar")}>
                <div className={getClassName(kind, "titleText")}>
                  {title}
                </div>
              </div>
              <div className={getClassName(kind, "contentBody")}>
                <TButtonScroller 
                  boxHeight={460} 
                  width={844} 
                  kind={kind}
                >
                  <div
                    className={getClassName(kind, "scrollerContent")}
                    dangerouslySetInnerHTML={{ __html: text }}
                  />
                </TButtonScroller>
              </div>
            </div>
            <ButtonContainerComp className={getClassName(kind, "buttonContainer")}>
              {showAgreeButton && (
                <TButton
                  className={getClassName(kind, "agreeButton")}
                  onClick={onAgreeClick}
                  spotlightId="figma-terms-agree"
                  type="popup"
                >
                  {$L('Agree')}
                </TButton>
              )}
              <TButton
                className={getClassName(kind, "closeButton")}
                onClick={onClose}
                spotlightId="figma-terms-close"
                type="popup"
              >
                {$L('Close')}
              </TButton>
            </ButtonContainerComp>
          </div>
        )}
      </Container>
    </Alert>
  );
}
