import { useEffect, useMemo, useState } from "react";
import { useParams } from "react-router-dom";
import { getJSON, itemsOrEmpty, readJSONCache, type Category } from "../../api";
import { AssetStreamPage } from "../../components/AssetStreamPage";
import { langQuery, useI18n } from "../../i18n";
import { cleanCategoryDisplayName } from "../../utils/categoryDisplay";

export function CategoryPage() {
  const { slug = "" } = useParams();
  const { lang } = useI18n();
  const [title, setTitle] = useState<string>(slug);
  const scope = useMemo(() => ({ kind: "category" as const, slug }), [slug]);

  useEffect(() => {
    if (!slug) return;
    let cancelled = false;
    const categoriesUrl = `/api/categories?lang=${encodeURIComponent(
      langQuery(lang),
    )}`;
    const applyTitle = (cats: Category[]) =>
      setTitle(
        cleanCategoryDisplayName(
          itemsOrEmpty(cats).find((x) => x.slug === slug)?.name ?? slug,
        ),
      );

    setTitle(slug);
    const cachedCategories = readJSONCache<Category[]>(categoriesUrl);
    if (cachedCategories) applyTitle(cachedCategories);

    getJSON<Category[]>(categoriesUrl)
      .then((cats) => {
        if (!cancelled) applyTitle(cats);
      })
      .catch(() => {
        if (!cancelled && !cachedCategories) setTitle(slug);
      });

    return () => {
      cancelled = true;
    };
  }, [slug, lang]);

  return <AssetStreamPage title={title || slug} scope={scope} />;
}
