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

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

import Spotlight from "@enact/spotlight";
import SpotlightContainerDecorator from "@enact/spotlight/SpotlightContainerDecorator";

import { setShowPopup } from "../../../actions/commonActions";
import {
  sendLogDetail,
  sendLogGNB,
  sendLogProductDetail,
  sendLogShopByMobile,
  sendLogTotalRecommend,
} from "../../../actions/logActions";
import TButton from "../../../components/TButton/TButton";
import TQRCode from "../../../components/TQRCode/TQRCode";
import * as Config from "../../../utils/Config";
import {
  $L,
  formatGMTString,
  formatLocalDateTime,
} from "../../../utils/helperMethods";
import IndicatorOptions from "../components/indicator/IndicatorOptions";
import ThemeIndicator from "../components/indicator/ThemeIndicator";
import StarRating from "../components/StarRating";
import css from "./HotelProduct.module.less";

const Container = SpotlightContainerDecorator(
  { enterTo: "default-element", preserveld: true },
  "div"
);
export default function HotelOption({
  isOnTop,
  panelInfo,
  launchedFromPlayer,
  selectedIndex,
  setSelectedIndex,
  isLoading,
  shopByMobileLogRef,
  isYouMayLikeOpened,
}) {
  const dispatch = useDispatch();

  const hotelInfos = useSelector(
    (state) => state.home.themeCurationHotelDetailData
  );
  const hotelData = useSelector((state) => state.home.hotelData);
  const nowMenu = useSelector((state) => state.common.nowMenu);
  const { popupVisible } = useSelector((state) => state.common.popup);
  const [label, setLabel] = useState("");
  const [amenitiesInfos, setAmenitiesInfos] = useState();

  const timerRef = useRef(null);

  const tooltipDes = $L("Scan for more information about the product.");

  const selectedHotelInfo = useMemo(() => {
    if (hotelData) {
      const { curationId, curationNm, hotelInfos, patncNm, patnrId } =
        hotelData.hotelInfo;

      return {
        curationId,
        curationNm,
        expsOrd: `${selectedIndex + 1}`,
        hotelInfo: hotelInfos[selectedIndex],
        patncNm,
        patnrId,
      };
    }

    return {};
  }, [hotelData, hotelInfos, selectedIndex]);

  useEffect(() => {
    const menu = isYouMayLikeOpened
      ? `${Config.LOG_MENU.DETAIL_PAGE_TRAVEL_THEME_DETAIL}/${Config.LOG_MENU.DETAIL_PAGE_YOU_MAY_LIKE}`
      : Config.LOG_MENU.DETAIL_PAGE_TRAVEL_THEME_DETAIL;

    dispatch(sendLogGNB(menu));
  }, [isYouMayLikeOpened]);

  useEffect(() => {
    if (selectedHotelInfo && Object.keys(selectedHotelInfo).length > 0) {
      const params = {
        befPrice: selectedHotelInfo?.hotelInfo?.hotelDetailInfo?.price ?? "",
        curationId: selectedHotelInfo?.curationId ?? "",
        curationNm: selectedHotelInfo?.curationNm ?? "",
        expsOrd: selectedHotelInfo?.expsOrd ?? "",
        inDt: "",
        lastPrice: selectedHotelInfo?.hotelInfo?.hotelDetailInfo?.price ?? "",
        lgCatCd: "",
        lgCatNm: "",
        linkTpCd: panelInfo?.linkTpCd ?? "",
        logTpNo: Config.LOG_TP_NO.PRODUCT.PRODUCT_DETAIL_IMAGE,
        patncNm: selectedHotelInfo?.patncNm ?? "",
        patnrId: selectedHotelInfo?.patnrId ?? "",
        prdtId: selectedHotelInfo?.hotelInfo?.hotelId ?? "",
        prdtNm: selectedHotelInfo?.hotelInfo?.hotelNm ?? "",
        revwGrd: selectedHotelInfo?.hotelInfo?.hotelDetailInfo?.revwGrd ?? "",
        rewdAplyFlag: "N",
        tsvFlag: "N",
      };

      timerRef.current = setTimeout(
        () => dispatch(sendLogProductDetail(params)),
        1000
      );
    }

    return () => clearTimeout(timerRef.current);
  }, [selectedHotelInfo]);

  useEffect(() => {
    if (hotelData) {
      const { hotelInfo } = hotelData;

      const params = {
        curationId: hotelInfo?.curationId ?? "",
        curationNm: hotelInfo?.curationNm ?? "",
        inDt: formatGMTString(new Date()),
        linkTpCd: panelInfo?.linkTpCd ?? "",
        logTpNo: Config.LOG_TP_NO.DETAIL.TRAVEL_DETAIL,
        patncNm: hotelInfo?.patncNm ?? "",
        patnrId: hotelInfo?.patnrId ?? "",
      };

      return () => dispatch(sendLogDetail(params));
    }
  }, [hotelData]);

  useEffect(() => {
    let label = "";
    let rating = hotelInfos[selectedIndex]?.hotelDetailInfo.revwGrd;

    if (rating !== undefined) {
      if (rating <= 2.4) {
        label = $L("Fair");
      } else if (rating >= 2.5 && rating <= 3.4) {
        label = $L("Good");
      } else if (rating >= 3.5 && rating <= 4.4) {
        label = $L("Very Good");
      } else if (rating >= 4.5 && rating <= 5) {
        label = $L("Excellent");
      }
    }

    setLabel(label);
  }, [selectedIndex, hotelInfos]);

  useEffect(() => {
    if (hotelData) {
      getAmenitiesInfo();
    }
  }, [hotelData, selectedIndex]);

  const handleSMSClick = useCallback(() => {
    dispatch(setShowPopup(Config.ACTIVE_POPUP.smsPopup));
    const logParams = {
      status: "open",
      nowMenu: nowMenu,
      partner: selectedHotelInfo.patncNm,
      price: selectedHotelInfo.hotelInfo?.hotelDetailInfo?.price,
      productTitle: selectedHotelInfo.hotelInfo?.hotelDetailInfo?.hotelNm,
      productId: selectedHotelInfo.hotelInfo?.hotelDetailInfo?.hotelId,
      contextName: Config.LOG_CONTEXT_NAME.SHOPBYMOBILE,
      messageId: Config.LOG_MESSAGE_ID.SMB,
    };
    dispatch(sendLogTotalRecommend(logParams));
    dispatch(
      sendLogTotalRecommend({
        menu: Config.LOG_MENU.DETAIL_PAGE_TRAVEL_THEME_DETAIL,
        buttonTitle: "Shop By Mobile",
        contextName: Config.LOG_CONTEXT_NAME.DETAILPAGE,
        messageId: Config.LOG_MESSAGE_ID.BUTTONCLICK,
      })
    );

    const params = {
      befPrice: selectedHotelInfo.hotelInfo?.hotelDetailInfo?.price,
      curationId: selectedHotelInfo.curationId,
      curationNm: selectedHotelInfo.curationNm,
      evntId: "",
      evntNm: "",
      lastPrice: selectedHotelInfo.hotelInfo?.hotelDetailInfo?.price,
      lgCatCd: "",
      lgCatNm: "",
      liveFlag: "N",
      locDt: formatLocalDateTime(new Date()),
      logTpNo: Config.LOG_TP_NO.SHOP_BY_MOBILE.SHOP_BY_MOBILE,
      mbphNoFlag: "N",
      patncNm: selectedHotelInfo.patncNm,
      patnrId: selectedHotelInfo.patnrId,
      prdtId: selectedHotelInfo.hotelInfo?.hotelDetailInfo?.hotelId,
      prdtNm: selectedHotelInfo.hotelInfo?.hotelDetailInfo?.hotelNm,
      revwGrd: selectedHotelInfo.hotelInfo?.hotelDetailInfo?.revwGrd,
      rewdAplyFlag: "N",
      shopByMobileFlag: "Y",
      shopTpNm: "hotel",
      showId: "",
      showNm: "",
      trmsAgrFlag: "N",
      tsvFlag: "N",
    };

    dispatch(sendLogShopByMobile(params));
    shopByMobileLogRef.current = params;
  }, [dispatch, selectedHotelInfo, shopByMobileLogRef]);

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

  const getAmenitiesInfo = () => {
    const matchedData = new Set();
    const amenitiesMap = new Map();

    hotelData.amenities.forEach((item) => {
      amenitiesMap.set(item.amntId, item);
    });

    hotelInfos[selectedIndex]?.hotelDetailInfo.amenities.forEach((amntId) => {
      if (amenitiesMap.has(amntId) && matchedData.size < 10) {
        matchedData.add(amenitiesMap.get(amntId));
      }
    });

    let amenitiesArr = Array.from(matchedData);
    amenitiesArr = amenitiesArr.filter((item, index, self) => {
      return index === self.findIndex((t) => t.lgAmntNm === item.lgAmntNm);
    });

    setAmenitiesInfos(amenitiesArr);
  };

  const todayFormattedString = useMemo(() => {
    const nights = hotelInfos[selectedIndex]?.hotelDetailInfo.nights;
    const adultsCount = hotelInfos[selectedIndex]?.hotelDetailInfo.adultsCount;

    return $L("Today, {nights} Nights {adultsCount} Adults")
      .replace("{nights}", nights)
      .replace("Nights", "Night" + (nights >= 2 ? "s" : ""))
      .replace("{adultsCount}", adultsCount)
      .replace("Adults", "Adult" + (adultsCount >= 2 ? "s" : ""));
  }, [hotelInfos, selectedIndex]);

  useEffect(() => {
    Spotlight.focus("indicator-image-" + selectedIndex);
  }, [hotelInfos, isLoading]);

  useEffect(() => {
    let spotFocus = null;
    if (!popupVisible) {
      spotFocus = setTimeout(() => {
        Spotlight.focus("shopbymobile_Btn");
      }, 0);
    }
    return () => {
      clearTimeout(spotFocus);
    };
  }, [popupVisible]);

  return (
    <>
      {hotelInfos && (
        <>
          <Container className={css.themeContainer}>
            <ThemeIndicator
              themeProductInfos={hotelInfos}
              selectedIndex={selectedIndex}
              setSelectedIndex={setSelectedIndex}
              thumbnailUrls={hotelInfos[selectedIndex]?.hotelDetailInfo.imgUrls}
              launchedFromPlayer={launchedFromPlayer}
              isOnTop={isOnTop}
            />

            <IndicatorOptions
              address={hotelInfos[selectedIndex]?.hotelDetailInfo.hotelAddr}
            />
          </Container>
          <div>
            <div className={css.optionContainer}>
              <div className={css.topLayer}>
                <img src={hotelData?.hotelInfo.patncLogoPath} alt="" />

                <div className={css.rating}>
                  <StarRating
                    rating={hotelInfos[selectedIndex]?.hotelDetailInfo.revwGrd}
                  />
                  <span className={css.line} /> <div>{label}</div>
                </div>
              </div>
              <div className={css.title}>
                [{hotelInfos[selectedIndex]?.hotelDetailInfo.hotelType}]&nbsp;
                {hotelInfos[selectedIndex]?.hotelNm}
              </div>
              <div className={css.amenitiesCotainer}>
                {amenitiesInfos &&
                  amenitiesInfos.map((item) => (
                    <div className={css.amenitiesBox} key={item.amntId}>
                      <img src={item.lgAmntImgUrl} alt="" />
                      <p>{item.lgAmntNm}</p>
                    </div>
                  ))}
              </div>
              <div className={css.bottomLayer}>
                <div>
                  <div className={css.today}>{todayFormattedString}</div>
                  <div
                    className={css.roomType}
                    aria-label={
                      hotelInfos[selectedIndex]?.hotelDetailInfo.roomType
                    }
                  >
                    {hotelInfos[selectedIndex]?.hotelDetailInfo.roomType}
                  </div>
                  <div className={css.price}>
                    <div>{$L("From")}</div>
                    <p>
                      <Price />
                    </p>
                  </div>
                </div>
                <div className={css.qrcodeContainer}>
                  {/* 호텔 QRCode 데이터만 서버에서 다르게 내려주고있어서 에러남 / 해결되면 주석제거 */}
                  <TQRCode
                    text={hotelInfos[selectedIndex]?.qrcodeUrl}
                    width="160"
                    height="160"
                  />
                  <div className={css.tooltip}>
                    <div className={css.tooltipBody}>{tooltipDes}</div>
                  </div>
                </div>
              </div>
              <TButton
                className={css.tbutton}
                size="extra"
                onClick={handleSMSClick}
                spotlightId="shopbymobile_Btn"
              >
                {$L("SEE MORE")}
              </TButton>
            </div>
          </div>
        </>
      )}
    </>
  );
}
