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

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

import Spotlight from "@enact/spotlight";
import { setContainerLastFocusedElement } from "@enact/spotlight/src/container";

import {
  changeAppStatus,
  changeLocalSettings,
  setHidePopup,
} from "../../actions/commonActions";
import { clearCouponInfo } from "../../actions/couponActions";
import { getDeviceAdditionInfo } from "../../actions/deviceActions";
import {
  clearThemeDetail,
  getThemeCurationDetailInfo,
  getThemeHotelDetailInfo,
} from "../../actions/homeActions";
import {
  getMainCategoryDetail,
  getMainYouMayLike,
} from "../../actions/mainActions";
import { popPanel, updatePanel } from "../../actions/panelActions";
import { finishVideoPreview } from "../../actions/playActions";
import {
  clearProductDetail,
  getProductGroup,
  getProductImageLength,
  getProductOptionId,
} from "../../actions/productActions";
import MobileSendPopUp from "../../components/MobileSend/MobileSendPopUp";
import TBody from "../../components/TBody/TBody";
import THeader from "../../components/THeader/THeader";
import TPanel from "../../components/TPanel/TPanel";
import * as Config from "../../utils/Config";
import { panel_names } from "../../utils/Config";
import { $L, getQRCodeUrl } from "../../utils/helperMethods";
import css from "./DetailPanel.module.less";
import GroupProduct from "./GroupProduct/GroupProduct";
import SingleProduct from "./SingleProduct/SingleProduct";
import ThemeProduct from "./ThemeProduct/ThemeProduct";
import UnableProduct from "./UnableProduct/UnableProduct";
import YouMayLike from "./YouMayLike/YouMayLike";
import { now } from "lodash";

export default function DetailPanel({ panelInfo, isOnTop, spotlightId }) {
  const dispatch = useDispatch();

  const productData = useSelector((state) => state.main.productData);
  const themeData = useSelector((state) => state.home.productData);
  const hotelData = useSelector((state) => state.home.hotelData);
  const isLoading = useSelector(
    (state) => state.common.appStatus?.showLoadingPanel?.show
  );
  const themeProductInfos = useSelector(
    (state) => state.home.themeCurationDetailInfoData
  );
  const hotelInfos = useSelector(
    (state) => state.home.themeCurationHotelDetailData
  );
  const localRecentItems = useSelector(
    (state) => state.localSettings?.recentItems
  );
  const youmaylikeData = useSelector((state) => state.main.youmaylikeData);
  const { httpHeader } = useSelector((state) => state.common);
  const deviceInfo = useSelector((state) => state.device.deviceInfo);

  const serverHOST = useSelector((state) => state.common.appStatus.serverHOST);
  const serverType = useSelector((state) => state.localSettings.serverType);
  const { entryMenu, nowMenu } = useSelector((state) => state.common.menu);
  const groupInfos = useSelector((state) => state.product.groupInfo);
  const productInfo = useSelector((state) => state.main.productData);
  const { popupVisible, activePopup } = useSelector(
    (state) => state.common.popup
  );
  const webOSVersion = useSelector(
    (state) => state.common.appStatus.webOSVersion
  );

  const panels = useSelector((state) => state.panels.panels);
  const [lgCatCd, setLgCatCd] = useState("");
  const [isYouMayLikeOpened, setIsYouMayLikeOpened] = useState(false);
  const [selectedIndex, setSelectedIndex] = useState(0);

  const shopByMobileLogRef = useRef(null);

  useEffect(() => {
    dispatch(getProductOptionId(undefined));
    if (panelInfo?.type === "hotel") {
      dispatch(
        getThemeHotelDetailInfo({
          patnrId: panelInfo?.patnrId,
          curationId: panelInfo?.curationId,
        })
      );
    }

    if (panelInfo?.type === "theme") {
      dispatch(
        getThemeCurationDetailInfo({
          patnrId: panelInfo?.patnrId,
          curationId: panelInfo?.curationId,
          bgImgNo: panelInfo?.bgImgNo,
        })
      );
    }

    if (panelInfo?.prdtId && !panelInfo?.curationId) {
      dispatch(
        getMainCategoryDetail({
          patnrId: panelInfo?.patnrId,
          prdtId: panelInfo?.prdtId,
          liveReqFlag: panelInfo?.liveReqFlag ? panelInfo?.liveReqFlag : "N",
        })
      );
    }
    dispatch(getDeviceAdditionInfo());
  }, [
    dispatch,
    panelInfo.liveReqFlag,
    panelInfo.curationId,
    panelInfo.prdtId,
    panelInfo.type,
    panelInfo.patnrId,
  ]);

  useEffect(() => {
    if (lgCatCd) {
      dispatch(
        getMainYouMayLike({
          lgCatCd: lgCatCd,
          exclCurationId: panelInfo?.curationId,
          exclPatnrId: panelInfo?.patnrId,
          exclPrdtId: panelInfo?.prdtId,
          catDpTh3:
            panelInfo?.type === "theme"
              ? themeProductInfos[selectedIndex]?.catDpTh3
              : productData?.catDpTh3,
          catDpTh4:
            panelInfo?.type === "theme"
              ? themeProductInfos[selectedIndex]?.catDpTh4
              : productData?.catDpTh4,
        })
      );
    }
  }, [panelInfo?.curationId, panelInfo?.patnrId, panelInfo?.prdtId, lgCatCd]);

  useEffect(() => {
    if (productData?.pmtSuptYn === "Y" && productData?.grPrdtProcYn === "Y") {
      dispatch(
        getProductGroup({
          patnrId: panelInfo?.patnrId,
          prdtId: panelInfo?.prdtId,
        })
      );
    }
  }, [productData]);

  useEffect(() => {
    if (
      themeProductInfos &&
      themeProductInfos.length > 0 &&
      panelInfo?.themePrdtId
    ) {
      for (let i = 0; i < themeProductInfos.length; i++) {
        if (themeProductInfos[i].prdtId === panelInfo?.themePrdtId) {
          setSelectedIndex(i);
        }
      }
    }

    if (hotelInfos && hotelInfos.length > 0 && panelInfo?.themeHotelId) {
      for (let i = 0; i < hotelInfos.length; i++) {
        if (hotelInfos[i].hotelId === panelInfo?.themeHotelId) {
          setSelectedIndex(i);
        }
      }
    }
  }, [
    themeProductInfos,
    hotelInfos,
    panelInfo?.themePrdtId,
    panelInfo?.themeHotelId,
  ]);

  const { detailUrl } = useMemo(() => {
    return getQRCodeUrl({
      serverHOST,
      serverType,
      index: deviceInfo?.dvcIndex,
      patnrId: productInfo?.patnrId,
      prdtId: productInfo?.prdtId,
      entryMenu: entryMenu,
      nowMenu: nowMenu,
      liveFlag: "Y",
      qrType: "billingDetail",
    });
  }, [serverHOST, serverType, deviceInfo, entryMenu, productInfo]);

  const onSpotlightUpTButton = (e) => {
    e.stopPropagation();
    Spotlight.focus("spotlightId_backBtn");
  };

  const onClick = useCallback(
    (isCancelClick) => (ev) => {
      dispatch(finishVideoPreview());
      dispatch(popPanel(panel_names.DETAIL_PANEL));

      if (panels.length === 4 && panels[1]?.name === panel_names.PLAYER_PANEL) {
        dispatch(
          updatePanel({
            name: panel_names.PLAYER_PANEL,
            panelInfo: {
              thumbnail: panelInfo.thumbnailUrl,
            },
          })
        );
      }

      if (isCancelClick) {
        ev.stopPropagation();
      }
    },
    [dispatch, panelInfo, panels]
  );

  const handleSMSonClose = useCallback(() => {
    dispatch(setHidePopup());
    setTimeout(() => {
      Spotlight.focus("spotlightId_backBtn");
      Spotlight.focus("shopbymobile_Btn");
    }, 0);
  }, [dispatch]);

  const saveToLocalSettings = useCallback(() => {
    let recentItems = [];
    const prdtId =
      themeProductInfos &&
      themeProductInfos.length > 0 &&
      panelInfo?.type === "theme"
        ? themeProductInfos[selectedIndex].prdtId
        : panelInfo?.prdtId;

    if (localRecentItems) {
      recentItems = [...localRecentItems];
    }

    const currentDate = new Date();

    const formattedDate = `${
      currentDate.getMonth() + 1
    }/${currentDate.getDate()}`;

    const existingProductIndex = recentItems.findIndex((item) => {
      return item.prdtId === prdtId;
    });

    if (existingProductIndex !== -1) {
      recentItems.splice(existingProductIndex, 1);
    }

    recentItems.push({
      prdtId: prdtId,
      patnrId: panelInfo?.patnrId,
      date: formattedDate,
      expireTime: currentDate.getTime() + 1000 * 60 * 60 * 24 * 14,
      cntryCd: httpHeader["X-Device-Country"],
    });

    if (recentItems.length >= 51) {
      const data = [...recentItems];
      dispatch(changeLocalSettings({ recentItems: data.slice(1) }));
    } else {
      dispatch(changeLocalSettings({ recentItems }));
    }
  }, [
    panelInfo?.prdtId,
    httpHeader,
    localRecentItems,
    dispatch,
    selectedIndex,
    themeProductInfos,
  ]);

  const getlgCatCd = useCallback(() => {
    if (productData && !panelInfo?.curationId) {
      setLgCatCd(productData.catCd);
    } else if (
      themeProductInfos &&
      themeProductInfos[selectedIndex]?.pmtSuptYn === "N" &&
      panelInfo?.curationId
    ) {
      setLgCatCd(themeProductInfos[selectedIndex]?.catCd);
    } else {
      setLgCatCd("");
    }
  }, [productData, themeProductInfos, selectedIndex, panelInfo?.curationId]);

  const mobileSendPopUpProductImg = useMemo(() => {
    if (panelInfo?.type === "theme" && themeProductInfos) {
      return themeProductInfos[selectedIndex]?.imgUrls600[0];
    } else if (panelInfo?.type === "hotel" && hotelInfos) {
      return hotelInfos[selectedIndex]?.hotelImgUrl;
    } else {
      return productData?.imgUrls600[0];
    }
  }, [
    themeProductInfos,
    hotelInfos,
    selectedIndex,
    productData,
    panelInfo?.type,
  ]);

  const mobileSendPopUpSubtitle = useMemo(() => {
    if (panelInfo?.type === "theme" && themeProductInfos) {
      return themeProductInfos[selectedIndex]?.prdtNm;
    } else if (panelInfo?.type === "hotel" && hotelInfos) {
      return hotelInfos[selectedIndex]?.hotelNm;
    } else {
      return productData?.prdtNm;
    }
  }, [
    themeProductInfos,
    hotelInfos,
    selectedIndex,
    productData,
    panelInfo?.type,
  ]);

  const isBillingProductVisible = useMemo(() => {
    return (
      productData?.pmtSuptYn === "Y" &&
      productData?.grPrdtProcYn === "N" &&
      panelInfo?.prdtId &&
      webOSVersion >= "6.0"
    );
  }, [productData, webOSVersion, panelInfo?.prdtId]);

  const isUnavailableProductVisible = useMemo(() => {
    return (
      productData?.pmtSuptYn === "N" ||
      (productData?.pmtSuptYn === "Y" &&
        productData?.grPrdtProcYn === "N" &&
        webOSVersion < "6.0" &&
        panelInfo?.prdtId)
    );
  }, [productData, webOSVersion, panelInfo?.prdtId]);

  const isGroupProductVisible = useMemo(() => {
    return (
      productData?.pmtSuptYn === "Y" &&
      productData?.grPrdtProcYn === "Y" &&
      groupInfos &&
      groupInfos.length > 0
    );
  }, [productData, groupInfos]);

  const isTravelProductVisible = useMemo(() => {
    return panelInfo?.curationId && (hotelInfos || themeData);
  }, [panelInfo?.curationId, hotelInfos, themeData]);

  const Price = () => {
    return (
      <>
        {hotelInfos[selectedIndex]?.hotelDetailInfo.currencySign}
        {hotelInfos[selectedIndex]?.hotelDetailInfo.price}
      </>
    );
  };

  useEffect(() => {
    getlgCatCd();
  }, [themeProductInfos, productData, panelInfo, selectedIndex]);

  useEffect(() => {
    if (panelInfo && panelInfo?.patnrId && panelInfo?.prdtId) {
      saveToLocalSettings();
    }
  }, [panelInfo, selectedIndex]);

  useEffect(() => {
    if (
      ((themeProductInfos && themeProductInfos.length > 0) ||
        (hotelInfos && hotelInfos.length > 0)) &&
      selectedIndex !== undefined
    ) {
      if (panelInfo?.type === "theme") {
        const imgUrls600 = themeProductInfos[selectedIndex]?.imgUrls600 || [];
        dispatch(getProductImageLength({ imageLength: imgUrls600.length }));
        return;
      }
      if (panelInfo?.type === "hotel") {
        const imgUrls600 = hotelInfos[selectedIndex]?.imgUrls600 || [];
        dispatch(getProductImageLength({ imageLength: imgUrls600.length }));
      }
    }
  }, [dispatch, themeProductInfos, selectedIndex, hotelInfos]);

  useEffect(() => {
    return () => {
      dispatch(clearProductDetail());
      dispatch(clearThemeDetail());
      dispatch(clearCouponInfo());
      setContainerLastFocusedElement(null, ["indicator-GridListContainer"]);
    };
  }, [dispatch]);

  return (
    <>
      <TPanel
        isTabActivated={false}
        className={css.detailPanelWrap}
        handleCancel={onClick(true)}
        spotlightId={spotlightId}
      >
        <THeader
          className={css.header}
          title={
            (panelInfo?.prdtId && productData?.prdtNm) ||
            (panelInfo?.type === "hotel" && hotelData?.hotelInfo.curationNm) ||
            (panelInfo?.type === "theme" && themeData?.themeInfo[0]?.curationNm)
          }
          onBackButton
          onClick={onClick(false)}
          spotlightDisabled={isLoading}
          onSpotlightUp={onSpotlightUpTButton}
          onSpotlightLeft={onSpotlightUpTButton}
          marqueeDisabled={false}
          ariaLabel={
            (panelInfo?.prdtId && productData?.prdtNm) ||
            (panelInfo?.type === "hotel" && hotelData?.hotelInfo.curationNm) ||
            (panelInfo?.type === "theme" && themeData?.themeInfo[0]?.curationNm)
          }
        />
        <TBody
          className={css.tbody}
          scrollable={false}
          spotlightDisabled={isLoading}
          isDefaultContainer
        >
          {!isLoading && (
            <>
              {/* 결제가능상품 영역 */}
              {isBillingProductVisible && (
                <SingleProduct
                  isOnTop={isOnTop}
                  panelInfo={panelInfo}
                  selectedPatnrId={panelInfo?.patnrId}
                  selectedPrdtId={panelInfo?.prdtId}
                  selectedIndex={selectedIndex}
                  setSelectedIndex={setSelectedIndex}
                  shopByMobileLogRef={shopByMobileLogRef}
                  isYouMayLikeOpened={isYouMayLikeOpened}
                  isBillingProductVisible={isBillingProductVisible}
                  detailQRCodeUrl={detailUrl}
                  logMenu={Config.LOG_MENU.DETAIL_PAGE_BILLING_PRODUCT_DETAIL}
                />
              )}
              {/* 구매불가상품 영역 */}
              {isUnavailableProductVisible && (
                <UnableProduct
                  isOnTop={isOnTop}
                  panelInfo={panelInfo}
                  selectedPatnrId={panelInfo?.patnrId}
                  selectedPrdtId={panelInfo?.prdtId}
                  selectedIndex={selectedIndex}
                  setSelectedIndex={setSelectedIndex}
                  shopByMobileLogRef={shopByMobileLogRef}
                  isYouMayLikeOpened={isYouMayLikeOpened}
                  logMenu={Config.LOG_MENU.DETAIL_PAGE_PRODUCT_DETAIL}
                />
              )}
              {/* 그룹상품 영역 */}
              {isGroupProductVisible && (
                <GroupProduct
                  isOnTop={isOnTop}
                  panelInfo={panelInfo}
                  selectedPatnrId={panelInfo?.patnrId}
                  selectedPrdtId={panelInfo?.prdtId}
                  selectedIndex={selectedIndex}
                  setSelectedIndex={setSelectedIndex}
                  shopByMobileLogRef={shopByMobileLogRef}
                  isYouMayLikeOpened={isYouMayLikeOpened}
                />
              )}
              {/* 테마그룹상품 영역*/}
              {isTravelProductVisible && (
                <ThemeProduct
                  isOnTop={isOnTop}
                  panelInfo={panelInfo}
                  selectedCurationId={panelInfo?.curationId}
                  selectedCurationNm={panelInfo?.curationNm}
                  selectedIndex={selectedIndex}
                  selectedPatnrId={panelInfo?.patnrId}
                  setSelectedIndex={setSelectedIndex}
                  themeType={panelInfo?.type}
                  isLoading={isLoading}
                  shopByMobileLogRef={shopByMobileLogRef}
                  isYouMayLikeOpened={isYouMayLikeOpened}
                />
              )}
            </>
          )}
        </TBody>
      </TPanel>
      {lgCatCd && youmaylikeData && youmaylikeData.length > 0 && isOnTop && (
        <YouMayLike
          isUnable={
            productData?.pmtSuptYn === "N" ||
            panelInfo?.type === "hotel" ||
            panelInfo?.type === "theme"
          }
          panelInfo={panelInfo}
          setSelectedIndex={setSelectedIndex}
          productInfo={productData || themeProductInfos[selectedIndex]}
          setIsYouMayLikeOpened={setIsYouMayLikeOpened}
        />
      )}
      {activePopup === Config.ACTIVE_POPUP.smsPopup && (
        <MobileSendPopUp
          open={popupVisible}
          onClose={handleSMSonClose}
          title={$L("Send a purchase link for this item via SMS")}
          subTitle={mobileSendPopUpSubtitle}
          patncNm={
            panelInfo?.type === "theme" &&
            themeProductInfos &&
            themeProductInfos[selectedIndex]
              ? themeProductInfos[selectedIndex].patncNm
              : productData?.patncNm
          }
          productImg={mobileSendPopUpProductImg}
          patnrId={panelInfo?.patnrId}
          prdtId={
            panelInfo?.type === "theme" &&
            themeProductInfos &&
            themeProductInfos[selectedIndex]
              ? themeProductInfos[selectedIndex].prdtId
              : panelInfo?.prdtId
          }
          smsTpCd={panelInfo?.type === "hotel" ? "APP00205" : "APP00201"}
          curationId={panelInfo?.curationId}
          curationNm={panelInfo?.curationNm}
          hotelId={
            panelInfo?.type === "hotel" && hotelInfos[selectedIndex]?.hotelId
          }
          hotelNm={
            panelInfo?.type === "hotel" && hotelInfos[selectedIndex]?.hotelNm
          }
          hotelDtlUrl={
            panelInfo?.type === "hotel" &&
            hotelInfos[selectedIndex]?.hotelDetailInfo?.hotelDtlUrl
          }
          productPrice={panelInfo?.type === "hotel" && Price()}
          shopByMobileLogRef={shopByMobileLogRef}
          spotlightId="shopbymobile_Btn"
          smsText={productInfo?.pmtSuptYn === "Y" ? detailUrl : undefined}
        />
      )}
    </>
  );
}
