import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
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 FullScreenModal from "../FullScreenModal";
import { useDynamicSize } from "@/hooks/useDynamicSize";
import PDFViewer from "../PDFViewer";
import BackButton from "../pages/ABDesign/v1/ui/BackButton";
// 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, t } = useTranslation();
  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 handleCompatibilityPDF = () => {
    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 getUserPDFCompatibility = useCallback(async () => {
    const pdf = await api.getUserPDFCompatibility({
      token,
    });
    return pdf;
  }, [api, token]);

  const { data: PDFCompatibility } = useApiCall<UserPDF.ResponseGet>(
    getUserPDFCompatibility
  );

  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={t("au.web_onbording.start")}
              crossClickHandler={() => setIsShowOnboardingHome(false)}
            />
          </Onboarding>
          {!!PDFCompatibility?.url?.length && (
            <BlurringSubstrate
              style={{ color: "#fff" }}
              className={styles["content__buttons-item"]}
              clickHandler={handleCompatibilityPDF}
            >
              <strong>Your Personalized READING</strong>
            </BlurringSubstrate>
          )}
          <BlurringSubstrate
            style={{ color: "#fa71ea" }}
            className={styles["content__buttons-item"]}
            clickHandler={handleCompatibility}
          >
            {buttonTextFormatter(t("aura-money_compatibility-button"))}
          </BlurringSubstrate>
          <BlurringSubstrate
            style={{ color: "#00f0ff" }}
            className={styles["content__buttons-item"]}
            clickHandler={handleBreath}
          >
            {buttonTextFormatter(t("aura-10_breath-button"))}
          </BlurringSubstrate>
          <BlurringSubstrate
            style={{ color: "#FD433F" }}
            className={styles["content__buttons-item"]}
            clickHandler={handleMyHoroscope}
          >
            {buttonTextFormatter(
              t("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"]}>
              {t("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"]}>
                {t("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"]}
                >
                  {t("aura.personal_aura.button")}
                </Title>
                <p className={styles["content__daily-forecast-body"]}>
                  {forecast.body}
                </p>
              </div>
            ))}
        </div> */}
      </div>
      {/* </div> */}
    </section>
  );
}

export default HomePage;
