import { useEffect, useState } from "react";
import { getJSON, itemsOrEmpty, readJSONCache, type Category } from "../../api";
import { RecommendedCard } from "../../components/RecommendedCard";
import { SectionHeader } from "../../components/SectionHeader";
import { langQuery, useI18n } from "../../i18n";
import { sourceLanguageQuery } from "../../i18nLanguages";
import type { Post } from "../../types/post";
import {
  postToResource,
  type PostBackedResource,
} from "../../utils/postResourceAdapter";

export function OfficialRecommendationsPage() {
  const { t, lang } = useI18n();
  const [items, setItems] = useState<PostBackedResource[]>([]);
  const [err, setErr] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;
    const langParam = encodeURIComponent(langQuery(lang));
    const languageParam = encodeURIComponent(sourceLanguageQuery(lang));
    const categoriesUrl = `/api/categories?lang=${langParam}`;
    const recommendedUrl = `/api/posts/recommended?lang=${langParam}&language=${languageParam}&limit=100`;

    const applyItems = (
      categories: Category[],
      recommended: { items: Post[] },
    ) => {
      const cats = itemsOrEmpty(categories);
      setItems(
        itemsOrEmpty(recommended.items).map((post) =>
          postToResource(post, lang, cats),
        ),
      );
    };

    setErr(null);
    const cachedCategories = readJSONCache<Category[]>(categoriesUrl);
    const cachedRecommended = readJSONCache<{ items: Post[] }>(recommendedUrl);
    const showedCached = !!(cachedCategories && cachedRecommended);

    if (showedCached) applyItems(cachedCategories, cachedRecommended);

    Promise.all([
      getJSON<Category[]>(categoriesUrl),
      getJSON<{ items: Post[] }>(recommendedUrl),
    ])
      .then(([categories, recommended]) => {
        if (cancelled) return;
        applyItems(categories, recommended);
      })
      .catch((e) => {
        if (!cancelled && !showedCached) setErr(String(e));
      });

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

  if (err) {
    return (
      <div className="rounded-xl border border-red-900 bg-red-950/40 p-4 text-red-200">
        {err}
      </div>
    );
  }

  return (
    <section>
      <div className="mx-auto max-w-full px-4 md:max-w-[820px] md:px-0 lg:max-w-[1080px] xl:max-w-[1180px]">
        <SectionHeader title={t("officialSection")} />
      </div>
      <div className="mx-auto mt-7 grid max-w-full grid-cols-1 justify-items-center gap-3 px-4 min-[560px]:grid-cols-2 md:max-w-[820px] md:grid-cols-3 md:px-0 lg:max-w-[1080px] lg:grid-cols-4 xl:max-w-[1180px]">
        {items.map((item, index) => (
          <RecommendedCard
            key={item.id}
            r={item}
            visualIndex={index}
            useFigmaDesign
            layout="grid"
          />
        ))}
      </div>
    </section>
  );
}
