import { useNavigate } from "react-router-dom";
import { useTranslations } from "@/hooks/translations";
import routes from "@/routes";
import styles from "./styles.module.css";
import { UserPDF, useApi, useApiCall } from "@/api";
import { Asset } from "@/api/resources/Assets";
import { useCallback, useEffect, useRef, useState } from "react";
import BlurringSubstrate from "../BlurringSubstrate";
import EnergyValues from "../EnergyValues";
import { UserAura } from "@/api/resources/Auras";
import { useDispatch, useSelector } from "react-redux";
import {
  getCategoryIdByZodiacSign,
  getZodiacSignByDate,
} from "@/services/zodiac-sign";
import { actions, selectors } from "@/store";
import { getRandomArbitrary } from "@/services/random-value";
// import Title from "../Title";
// import { UserDailyForecast } from "@/api/resources/UserDailyForecasts";
import { EPathsFromHome } from "@/store/siteConfig";
import { buildFilename, saveFile } from "../WallpaperPage/utils";
import Onboarding from "../Onboarding";
import TextWithFinger from "../TextWithFinger";
// import Slider from "../Slider";
// import BestiesHoroscopeSlider, { Horoscope } from "../BestiesHoroscopeSlider";
// import PredictionMoonsSlider, {
//   IPredictionMoon,
// } from "../PredictionMoonsSlider";
import { predictionMoonsPeriods } from "@/data";
import { useDynamicSize } from "@/hooks/useDynamicSize";
import { PDFKey } from "@/api/resources/UserPDF";
import Loader, { LoaderColor } from "../Loader";
import { sleep } from "@/services/date";
import metricService, { EGoals, EMetrics } from "@/services/metric/metricService";
// import WallpapersZodiacSign from "../WallpapersZodiacSign";
// import ThermalSlider from "../ThermalSlider";
// import MoonPhaseTracker from "../MoonPhaseTracker";
// import EnergyVampirism from "../EnergyVampirism";
// import NameHoroscopeSlider from "../NameHoroscopeSlider";

const buttonTextFormatter = (text: string): JSX.Element => {
  const sentences = text.split(".");
  return (
    <>
      <strong>{sentences[0]}</strong>
      <span style={{ fontSize: "12px" }}>{sentences[1]}</span>
    </>
  );
};

function HomePage(): JSX.Element {
  const token = useSelector(selectors.selectToken);
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const buttonsRef = useRef<HTMLDivElement>(null);

  const { i18n, translate } = useTranslations();
  const locale = i18n.language;
  const birthdate = useSelector(selectors.selectBirthdate);
  const zodiacSign = getZodiacSignByDate(birthdate);
  const [asset, setAsset] = useState<Asset>();
  const [moonsAssets, setMoonsAssets] = useState<Asset[]>([]);
  moonsAssets;
  const api = useApi();

  const homeConfig = useSelector(selectors.selectHome);
  const isShowNavbar = homeConfig.isShowNavbar;
  const onboardingConfigHome = useSelector(selectors.selectOnboardingHome);

  const compatibilities = useSelector(selectors.selectCompatibilities);
  compatibilities;

  const user = useSelector(selectors.selectUser);
  user;

  const [isShowOnboardingHome, setIsShowOnboardingHome] = useState(
    !onboardingConfigHome?.isShown
  );

  // const [isShowPDF, setIsShowPDF] = useState(false);

  useEffect(() => {
    dispatch(
      actions.onboardingConfig.update({
        home: {
          isShown: true,
        },
      })
    );
  }, [dispatch]);

  const handlePDF = (pdf: UserPDF.ResponseGet | null) => {
    if (!pdf?.url?.length) return;
    window.location.href = pdf?.url;
    // setIsShowPDF(true);
  };

  const handleCompatibility = () => {
    dispatch(
      actions.siteConfig.update({
        home: { pathFromHome: EPathsFromHome.compatibility, isShowNavbar },
      })
    );
    navigate(routes.client.compatibility());
  };

  const handleBreath = () => {
    dispatch(
      actions.siteConfig.update({
        home: { pathFromHome: EPathsFromHome.breath, isShowNavbar },
      })
    );
    navigate(routes.client.breath());
  };

  const handleMyHoroscope = () => {
    navigate(routes.client.myHoroscopeResult());
  };

  const handleMagicBall = () => {
    navigate(routes.client.magicBall());
  };

  const assetsData = useCallback(async () => {
    const { asset_categories } = await api.getAssetCategories({ locale });
    const categoryId = getCategoryIdByZodiacSign(zodiacSign, asset_categories);
    const { assets } = await api.getAssets({
      category: String(categoryId || "1"),
    });
    return assets;
  }, [api, locale, zodiacSign]);

  const {
    data: assets,
    // isPending
  } = useApiCall<Asset[]>(assetsData);

  const getUserPDF = useCallback(
    async (key: PDFKey): Promise<UserPDF.IUserPDF> => {
      try {
        const pdf = await api.getUserPDF({
          token,
          key,
        });
        if (pdf?.status === "not_allowed") {
          return pdf;
        }
        if (!pdf?.url?.length || pdf.status !== "ready") {
          await sleep(5000);
          return getUserPDF(key);
        }
        return pdf;
      } catch (error) {
        console.error("Error: ", error);
        return {
          id: null,
          url: null,
          status: "not_allowed",
          type: key,
        };
      }
    },
    [api, token]
  );

  const getUserCompatibility = useCallback(async () => {
    return await getUserPDF(PDFKey.Compatibility);
  }, [getUserPDF]);

  const getUserPalmistry = useCallback(async () => {
    return await getUserPDF(PDFKey.Palmistry);
  }, [getUserPDF]);

  const { data: PDFCompatibility, isPending: isPendingCompatibilityPDF } =
    useApiCall<UserPDF.ResponseGet>(getUserCompatibility);

  const { data: PDFPalmistry, isPending: isPendingPalmistryPDF } =
    useApiCall<UserPDF.ResponseGet>(getUserPalmistry);

  const getIsPDFLoading = useCallback(
    (pdf: UserPDF.ResponseGet | null, isPending: boolean) => {
      return isPending || !pdf || !pdf.url?.length || pdf.status !== "ready";
    },
    []
  );

  useEffect(() => {
    if (assets) {
      setAsset(assets[getRandomArbitrary(0, assets?.length || 0)]);
    }
  }, [assets]);

  const auraData = useCallback(async () => {
    const { user_aura } = await api.getAuras({ token });
    return user_aura;
  }, [api, token]);

  const {
    data: aura,
    // isPending
  } = useApiCall<UserAura>(auraData);

  // const dailyForecastData = useCallback(async () => {
  //   const { user_daily_forecast } = await api.getDailyForecasts({ token });
  //   return user_daily_forecast;
  // }, [api, token]);

  // const {
  //   data: dailyForecast,
  //   // isPending
  // } = useApiCall<UserDailyForecast>(dailyForecastData);

  useEffect(() => {
    getMoonsImages();
  }, [api]);

  const getMoonsImages = async () => {
    const assets = (
      await api.getAssets({ category: String("au.prediction_moons") || "1" })
    ).assets;
    const randomAssets: Asset[] = [];
    for (let i = 0; i < predictionMoonsPeriods.length; i++) {
      const index = getRandomArbitrary(0, assets.length - 1);
      randomAssets.push(assets[index]);
      assets.splice(index, 1);
    }
    setMoonsAssets(randomAssets);
  };

  const downloadImg = () => {
    if (!asset) return;
    saveFile(asset.url.replace("http://", "https://"), buildFilename("1"));
  };

  // const downloadPDF = () => {
  //   if (!PDFCompatibility?.url) return;
  //   saveFile(
  //     PDFCompatibility?.url.replace("http://", "https://"),
  //     buildFilename("pdf-compatibility", "pdf")
  //   );
  // };

  // const handleBestiesHoroscope = (item: Horoscope) => {
  //   const { name, birthDate } = item;
  //   navigate(
  //     `${routes.client.horoscopeBestiesResult()}?name=${name}&birthDate=${birthDate}`
  //   );
  // };

  // const handleThermal = (item: Horoscope) => {
  //   const { name, birthDate } = item;
  //   navigate(
  //     `${routes.client.thermalResult()}?name=${name}&birthDate=${birthDate}`
  //   );
  // };

  // const handlePredictionMoon = (item: IPredictionMoon) => {
  //   const { period } = item;
  //   navigate(`${routes.client.predictionMoonResult()}?period=${period}`);
  // };

  // const handleMoonPhaseTracker = () => {
  //   navigate(`${routes.client.moonPhaseTracker()}?period=today`);
  // };

  // const handleEnergyVampirism = () => {
  //   navigate(`${routes.client.energyVampirismResult()}?period=today`);
  // };

  // const handleNameHoroscope = (item: IPredictionMoon) => {
  //   navigate(`${routes.client.nameHoroscopeResult()}?period=${item.period}`);
  // };

  const {
    // width,
    elementRef: pageRef,
  } = useDynamicSize({});

  return (
    <section
      className={`${styles.page} page`}
      style={{
        backgroundImage: `url(${asset?.url.replace("http://", "https://")})`,
      }}
      ref={pageRef}
    >
      {/* <FullScreenModal
        isOpen={isShowPDF}
        className={styles["pdf-modal"]}
        classNameContent={styles["pdf-modal__content"]}
      >
        <>
          <div className={styles["pdf-buttons"]}>
            <BackButton
              onClick={() => setIsShowPDF(false)}
              className={styles["close-pdf-button"]}
            />
            <div className={styles["pdf-save"]} onClick={downloadPDF} />
          </div>
          <PDFViewer
            width={width}
            file={PDFCompatibility?.url}
            className={styles["pdf-document"]}
          />
        </>
      </FullScreenModal> */}

      {/* <div
        className={styles.background}
        style={{
          backgroundImage: `url(${asset?.url.replace("http://", "https://")})`,
        }}
      > */}
      <div className={styles.header}>
        <BlurringSubstrate>
          <div className={styles["header__energies"]}>
            <div className={styles["header__energies-header"]}>
              <div className={styles["header__energies-aura"]}></div>
              <span className={styles["header__energies-title"]}>
                Your energy today
              </span>
            </div>
            {aura && <EnergyValues values={aura.stats} />}
          </div>
        </BlurringSubstrate>
        <div className={styles["header__save"]} onClick={downloadImg}>
          {/* <a href={asset?.url.replace('http://', 'https://')} download></a> */}
        </div>
      </div>
      <div
        className={styles.content}
        style={{
          marginTop: isShowNavbar
            ? "calc(100vh - 570px)"
            : "calc(100vh - 500px)",
        }}
      >
        <div
          ref={buttonsRef}
          className={`${styles["content__buttons"]} 
          `}
        // ${
        //   isShowNavbar ? styles["content__buttons--hidden"] : ""
        // }
        >
          <Onboarding
            targetRef={buttonsRef.current as HTMLDivElement}
            isShow={isShowOnboardingHome}
          >
            <TextWithFinger
              text={translate("au.web_onbording.start")}
              crossClickHandler={() => setIsShowOnboardingHome(false)}
            />
          </Onboarding>
          {PDFPalmistry?.status !== "not_allowed" && (
            <BlurringSubstrate
              style={{ color: "#fff" }}
              className={`${styles["content__buttons-item"]} ${getIsPDFLoading(PDFPalmistry, isPendingPalmistryPDF)
                ? styles["content__buttons-loading"]
                : ""
                }`}
              clickHandler={() => {
                metricService.reachGoal(EGoals.PDF_PALM_OPEN, [EMetrics.YANDEX, EMetrics.KLAVIYO]);
                handlePDF(PDFPalmistry)
              }}
            >
              <>
                {getIsPDFLoading(PDFPalmistry, isPendingPalmistryPDF) && (
                  <Loader
                    color={LoaderColor.White}
                    className={styles["buttons-loader"]}
                  />
                )}
                <strong>Your Palmistry READING</strong>
              </>
            </BlurringSubstrate>
          )}
          {PDFCompatibility?.status !== "not_allowed" && (
            <BlurringSubstrate
              style={{ color: "#fff" }}
              className={`${styles["content__buttons-item"]} ${getIsPDFLoading(PDFCompatibility, isPendingCompatibilityPDF)
                ? styles["content__buttons-loading"]
                : ""
                }`}
              clickHandler={() => {
                metricService.reachGoal(EGoals.PDF_COMP_OPEN, [EMetrics.YANDEX, EMetrics.KLAVIYO]);
                handlePDF(PDFCompatibility)
              }}
            >
              <>
                {getIsPDFLoading(
                  PDFCompatibility,
                  isPendingCompatibilityPDF
                ) && (
                    <Loader
                      color={LoaderColor.White}
                      className={styles["buttons-loader"]}
                    />
                  )}
                <strong>Your Personalized READING</strong>
              </>
            </BlurringSubstrate>
          )}
          <BlurringSubstrate
            style={{ color: "#fa71ea" }}
            className={styles["content__buttons-item"]}
            clickHandler={handleCompatibility}
          >
            {buttonTextFormatter(translate("aura-money_compatibility-button"))}
          </BlurringSubstrate>
          <BlurringSubstrate
            style={{ color: "#00f0ff" }}
            className={styles["content__buttons-item"]}
            clickHandler={handleBreath}
          >
            {buttonTextFormatter(translate("aura-10_breath-button"))}
          </BlurringSubstrate>
          <BlurringSubstrate
            style={{ color: "#FD433F" }}
            className={styles["content__buttons-item"]}
            clickHandler={handleMyHoroscope}
          >
            {buttonTextFormatter(
              translate("Receive an In-Depth Analysis and Today’s Horoscope")
            )}
          </BlurringSubstrate>
        </div>
        <div className={`${styles["content__buttons"]}`}>
          <div
            className={`${styles["content__aura"]}`}
            onClick={handleMagicBall}
          >
            <p className={styles["content__aura-text"]}>{"Get an answer"}</p>
          </div>
        </div>

        {/* SLIDERS */}
        {/* <div className={styles.sliders}>
          {!!compatibilities.length && (
            <div className={styles["slider"]}>
              <Title variant="h2" className={styles["sliders__title"]}>
                {"Your Besties' Horoscope"}
              </Title>
              <Slider>
                {compatibilities.map((item, index) => (
                  <BestiesHoroscopeSlider
                    data={item}
                    key={index}
                    onClick={() => {
                      handleBestiesHoroscope(item);
                    }}
                  />
                ))}
              </Slider>
            </div>
          )}
          <div className={styles["slider"]}>
            <Title variant="h2" className={styles["sliders__title"]}>
              {"Prediction Based on Your Moons"}
            </Title>
            <Slider>
              {predictionMoonsPeriods.map((item, index) => (
                <PredictionMoonsSlider
                  image={moonsAssets[index]?.url}
                  data={item}
                  key={index}
                  onClick={() => {
                    handlePredictionMoon(item);
                  }}
                />
              ))}
            </Slider>
          </div>
        </div> */}
        {/* END SLIDERS */}

        {/* <Title variant="h2" className={styles["sliders__title"]}>
          {"Energy Vampirism"}
        </Title>
        <EnergyVampirism onClick={handleEnergyVampirism} /> */}

        {/* SLIDERS */}
        {/* <div className={styles.sliders}>
          <div className={styles["slider"]}>
            <Title variant="h2" className={styles["sliders__title"]}>
              {translate("Your Name's Horoscope")}
            </Title>
            <Slider>
              {predictionMoonsPeriods.map((item, index) => (
                <NameHoroscopeSlider
                  data={{ ...item, name: user.username || "" }}
                  key={index}
                  onClick={() => {
                    handleNameHoroscope(item);
                  }}
                />
              ))}
            </Slider>
          </div>
        </div> */}
        {/* END SLIDERS */}

        {/* <Title variant="h2" className={styles["sliders__title"]}>
          {"AI-based unique Walpapers"}
        </Title>
        <WallpapersZodiacSign /> */}

        {/* SLIDERS */}
        {/* <div className={styles.sliders}>
          {!!compatibilities.length && (
            <div className={styles["slider"]}>
              <Title variant="h2" className={styles["sliders__title"]}>
                {translate("au.thermal_compatibility.result_title")}
              </Title>
              <Slider>
                {compatibilities.map((item, index) => (
                  <ThermalSlider
                    data={item}
                    key={index}
                    onClick={() => {
                      handleThermal(item);
                    }}
                  />
                ))}
              </Slider>
            </div>
          )}
        </div> */}
        {/* END SLIDERS */}

        {/* <MoonPhaseTracker onClick={handleMoonPhaseTracker} /> */}

        {/* <div className={styles["content__daily-forecast"]}>
          {dailyForecast &&
            dailyForecast.forecasts.map((forecast, index) => (
              <div
                className={styles["content__daily-forecast-item"]}
                key={index}
              >
                <Title
                  variant="h3"
                  className={styles["content__daily-forecast-title"]}
                >
                  {translate("aura.personal_aura.button")}
                </Title>
                <p className={styles["content__daily-forecast-body"]}>
                  {forecast.body}
                </p>
              </div>
            ))}
        </div> */}
      </div>
      {/* </div> */}
    </section>
  );
}

export default HomePage;
