import { useTranslation } from "react-i18next";
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 ThermalProps {
  data: Thermal;
  onClick: () => void;
}

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

function ThermalSlider({ data, onClick }: ThermalProps): JSX.Element {
  const api = useApi();
  const { i18n } = useTranslation();
  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);
      }
    })();
  }, [api, locale, zodiacSign]);

  return (
    <div
      className={styles.container}
      onClick={onClick}
    >
      <img className={styles.background} src={backgroundUrl} alt="background image" />
      <div className={styles["name-container"]}>
        <p>with {data.name}</p>
      </div>
      <span className={styles.period}>Today</span>
    </div>
  );
}

export default ThermalSlider;
