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

interface INameHoroscopeSliderProps {
  data: INameHoroscope;
  onClick: () => void;
}

export interface INameHoroscope {
  period: string;
  name: string;
}

function NameHoroscopeSlider({
  data,
  onClick,
}: INameHoroscopeSliderProps): JSX.Element {
  const api = useApi();
  const { i18n } = useTranslations();
  const locale = i18n.language;
  const birthDate = useSelector(selectors.selectBirthdate);
  const zodiacSign = useMemo(() => getZodiacSignByDate(birthDate), [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
      style={{ backgroundImage: `url(${backgroundUrl})` }}
      className={styles.container}
      onClick={onClick}
    >
      <p className={styles.period}>{data.period}</p>
      <p className={styles.name}>
        <b>{data.name}</b>
      </p>
    </div>
  );
}

export default NameHoroscopeSlider;
