import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import routes from "@/routes";
import styles from "./styles.module.css";
import { 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";

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

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

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

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

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

  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 { i18n } = useTranslation();
  const locale = i18n.language;
  const birthdate = useSelector(selectors.selectBirthdate);
  const zodiacSign = getZodiacSignByDate(birthdate);
  const [asset, setAsset] = useState<Asset>();
  const api = useApi();

  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);

  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);

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

  return (
    <section
      className={`${styles.page} page`}
      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>
            <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>
          </div>
        }
        <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"]}
                >
                  {/* {forecast.category} */}
                  {t("aura.personal_aura.button")}
                </Title>
                <p className={styles["content__daily-forecast-body"]}>
                  {forecast.body}
                </p>
              </div>
            ))}
        </div>
      </div>
    </section>
  );
}

export default HomePage;
