import { useTranslations } from "@/hooks/translations";
import styles from "./styles.module.css";
import { useApi } from "@/api";
import { getRandomArbitrary } from "@/services/random-value";
import { useEffect, useState } from "react";

interface IMoonPhaseTracker {
  onClick: () => void;
}

function MoonPhaseTracker({ onClick }: IMoonPhaseTracker): JSX.Element {
  const api = useApi();
  const { translate } = useTranslations();
  const [backgroundUrl, setBackgroundUrl] = useState("");

  const getImage = async () => {
    try {
      const categoryId = "au.moonse_phase";
      const assets = (
        await api.getAssets({ category: String(categoryId || "1") })
      ).assets;
      const randomAsset = assets[getRandomArbitrary(0, assets.length - 1)];
      setBackgroundUrl(randomAsset.url);
    } catch (error) {
      console.error("Error: ", error);
    }
  };

  useEffect(() => {
    getImage();
  }, []);

  const removeLastWord = (sentence: string): string => {
    const lastIndex = sentence.lastIndexOf(" ");
    return sentence.substring(0, lastIndex);
  };

  return (
    <div
      className={styles.container}
      style={{ backgroundImage: `url(${backgroundUrl})` }}
      onClick={onClick}
    >
      <p className={styles.text}>Today</p>
      <p className={styles.text}>
        Discover the {removeLastWord(translate("au.moonse_phase.result_title"))}
      </p>
      {/* <div className={styles.blur}></div> */}
    </div>
  );
}

export default MoonPhaseTracker;
