import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { getJSON, itemsOrEmpty, readJSONCache, type Category } from "../../api";
import { CategoryIcon } from "../../components/CategoryIcon";
import { SectionHeader } from "../../components/SectionHeader";
import { Skeleton } from "../../components/Skeleton";
import { langQuery, useI18n } from "../../i18n";
import { cleanCategoryDisplayName } from "../../utils/categoryDisplay";
import { Reveal } from "../../motion";

const FIGMA_CATEGORY_ORDER = [
  "project-ppt",
  "daily-class",
  "official-announcement",
  "academy-materials",
  "global-evangelism",
  "daily-poster",
  "community-tweets",
  "video-hub",
  "subsidy-policy",
  "how-to",
  "official-assets",
  "media-coverage",
  "academy-video",
  "general",
];

function figmaCategoryRank(category: Category): number {
  const index = FIGMA_CATEGORY_ORDER.indexOf(category.slug);
  return index === -1 ? FIGMA_CATEGORY_ORDER.length : index;
}

export function CategoriesPage() {
  const { t, lang } = useI18n();
  const [cats, setCats] = useState<Category[]>([]);
  const [err, setErr] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;
    const categoriesUrl = `/api/categories?lang=${encodeURIComponent(
      langQuery(lang),
    )}`;
    const applyCategories = (items: Category[]) =>
      setCats(
        itemsOrEmpty(items).sort(
          (a, b) => figmaCategoryRank(a) - figmaCategoryRank(b),
        ),
      );

    setErr(null);
    const cachedCategories = readJSONCache<Category[]>(categoriesUrl);
    if (cachedCategories) applyCategories(cachedCategories);

    getJSON<Category[]>(categoriesUrl)
      .then((items) => {
        if (!cancelled) applyCategories(items);
      })
      .catch((e) => {
        if (!cancelled && !cachedCategories) 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>
    );
  }

  const isLoading = cats.length === 0;

  return (
    <section>
      <SectionHeader title={t("categorySection")} />
      <div className="mt-7 grid grid-cols-3 gap-2 md:grid-cols-5 md:gap-3 lg:grid-cols-6 xl:grid-cols-7 xl:gap-4">
        {isLoading
          ? Array.from({ length: 14 }).map((_, i) => (
              <Skeleton key={i} className="h-[88px] rounded-xl" />
            ))
          : cats.map((category, index) => (
              <Reveal
                key={category.id}
                delay={Math.min(index, 8) * 0.05}
                className="h-[88px]"
              >
                <Link
                  to={`/category/${encodeURIComponent(category.slug)}`}
                  className="flex h-[88px] min-w-0 flex-col items-center justify-center gap-2 rounded-xl border border-[#27292E] bg-[#1D1E23] px-4 py-3 text-center outline-none transition hover:border-ark-gold/55 hover:bg-[#252630] focus-visible:ring-2 focus-visible:ring-ark-gold/80 focus-visible:ring-offset-2 focus-visible:ring-offset-ark-bg"
                >
                  <CategoryIcon
                    iconKey={category.iconKey}
                    categorySlug={category.slug}
                    className="h-9 w-9 shrink-0 text-ark-gold"
                  />
                  <div className="w-full text-center text-[13px] font-medium leading-[19.5px] text-white line-clamp-2">
                    {cleanCategoryDisplayName(category.name)}
                  </div>
                </Link>
              </Reveal>
            ))}
      </div>
    </section>
  );
}
