"use client";

import Image from "next/image";
import Link from "next/link";
import { useMemo, useState } from "react";
import type { Locale } from "@/content/site";

export type LibraryCardData = {
  slug: string;
  title: string;
  excerpt: string;
  category: string;
  tags: string[];
  coverImage: string;
  coverImageAlt: string;
  publishedAt: string;
  readingTime: string;
  href: string;
};

const labels = {
  fr: {
    all: "Tous",
    filters: "Filtrer les articles par catégorie",
    empty: "Aucun article n’est encore publié dans cette catégorie.",
    read: "Lire l’article",
    temporary: "Visuel temporaire",
  },
  en: {
    all: "All",
    filters: "Filter articles by category",
    empty: "No article has been published in this category yet.",
    read: "Read article",
    temporary: "Temporary visual",
  },
  ar: {
    all: "الكل",
    filters: "تصفية المقالات حسب الفئة",
    empty: "لا توجد مقالات منشورة في هذه الفئة حالياً.",
    read: "اقرأ المقال",
    temporary: "صورة مؤقتة",
  },
} satisfies Record<Locale, Record<string, string>>;

function formatDate(locale: Locale, value: string) {
  return new Intl.DateTimeFormat(locale === "ar" ? "ar-MA" : locale === "fr" ? "fr-FR" : "en-GB", {
    day: "numeric",
    month: "long",
    year: "numeric",
    timeZone: "UTC",
  }).format(new Date(`${value}T00:00:00Z`));
}

export function LibraryFilters({
  locale,
  articles,
}: {
  locale: Locale;
  articles: LibraryCardData[];
}) {
  const copy = labels[locale];
  const [activeCategory, setActiveCategory] = useState(copy.all);
  const categories = useMemo(
    () => [copy.all, ...Array.from(new Set(articles.map((article) => article.category)))],
    [articles, copy.all],
  );
  const visibleArticles = activeCategory === copy.all
    ? articles
    : articles.filter((article) => article.category === activeCategory);

  return (
    <div className="library-browser">
      {categories.length > 1 && (
        <div className="library-filters" role="group" aria-label={copy.filters}>
          {categories.map((category) => (
            <button
              key={category}
              type="button"
              aria-pressed={activeCategory === category}
              onClick={() => setActiveCategory(category)}
            >
              {category}
            </button>
          ))}
        </div>
      )}

      {visibleArticles.length > 0 ? (
        <div className="library-grid" aria-live="polite">
          {visibleArticles.map((article) => (
            <article className="library-card" key={article.slug}>
              <Link href={article.href} className="library-card-link" aria-label={`${copy.read}: ${article.title}`}>
                <span className="library-card-media">
                  <Image
                    src={article.coverImage}
                    alt={article.coverImageAlt}
                    fill
                    sizes="(max-width: 48rem) 100vw, (max-width: 75rem) 50vw, 33vw"
                  />
                  {!article.coverImage.startsWith("/assets/images/library/") && <small>{copy.temporary}</small>}
                </span>
                <span className="library-card-copy">
                  <span className="library-card-meta">
                    <span>{article.category}</span>
                    <span><time dateTime={article.publishedAt}>{formatDate(locale, article.publishedAt)}</time> · {article.readingTime}</span>
                  </span>
                  <strong>{article.title}</strong>
                  <span>{article.excerpt}</span>
                  <span className="text-link">{copy.read}</span>
                </span>
              </Link>
            </article>
          ))}
        </div>
      ) : (
        <p className="library-empty" role="status">{copy.empty}</p>
      )}
    </div>
  );
}
