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

interface BestiesHoroscopeSliderProps {
  data: Horoscope;
  onClick: () => void;
}

export interface Horoscope {
  name: string;
  birthDate: string;
}

function BestiesHoroscopeSlider({
  data,
  onClick
}: BestiesHoroscopeSliderProps): JSX.Element {
  const api = useApi();
  const { i18n, translate } = useTranslations();
  const locale = i18n.language;
  const zodiacSign = getZodiacSignByDate(data.birthDate);
  const [backgroundUrl, setBackgroundUrl] = useState("");

  useEffect(() => {
    (async () => {
      try {
        const { asset_categories } = await api.getAssetCategories({ locale });
        const categoryId = getCategoryIdByZodiacSign(
          zodiacSign,
          asset_categories
        );
        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);
      }
    })();
  }, []);

  return (
    <div
      className={styles.container}
      style={{
        background: `url(${backgroundUrl})`,
      }}
      onClick={onClick}
    >
      <p className={styles.text}>
        {translate("au.besties.result")}
        <b> {data.name}</b>
      </p>
    </div>
  );
}

export default BestiesHoroscopeSlider;
