"use client";

import Link from "next/link";
import { useMemo, useState } from "react";
import type { BlogPost, Locale } from "@/types/content";
import { localizedPath } from "@/lib/routing";

const PAGE_SIZE = 6;

export function InsightBrowser({ posts, locale }: { posts: BlogPost[]; locale: Locale }) {
  const years = useMemo(() => {
    const uniqueYears = new Set(posts.map((post) => getPostYear(post)).filter(Boolean));
    return Array.from(uniqueYears).sort((a, b) => Number(b) - Number(a));
  }, [posts]);
  const [activeYear, setActiveYear] = useState("all");
  const [page, setPage] = useState(1);

  const filteredPosts = useMemo(() => {
    return activeYear === "all" ? posts : posts.filter((post) => getPostYear(post) === activeYear);
  }, [activeYear, posts]);
  const pageCount = Math.max(1, Math.ceil(filteredPosts.length / PAGE_SIZE));
  const visiblePosts = filteredPosts.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);

  function selectYear(year: string) {
    setActiveYear(year);
    setPage(1);
  }

  return (
    <div className="insight-browser">
      <div className="insight-toolbar">
        <div className="story-filter insight-filter" aria-label={locale === "id" ? "Filter artikel berdasarkan tahun" : "Filter articles by year"}>
          <button className={activeYear === "all" ? "active" : ""} onClick={() => selectYear("all")} type="button">
            {locale === "id" ? "Semua Tahun" : "All Years"}
          </button>
          {years.map((year) => (
            <button className={activeYear === year ? "active" : ""} key={year} onClick={() => selectYear(year)} type="button">
              {year}
            </button>
          ))}
        </div>
        <p>
          {locale === "id"
            ? `${filteredPosts.length} artikel ditemukan`
            : `${filteredPosts.length} articles found`}
        </p>
      </div>

      <div className="listing-grid">
        {visiblePosts.map((post) => (
          <article className="card solution-card insight-card" key={post.slug}>
            <p className="eyebrow">Insight</p>
            <time dateTime={post.publishedAt}>{formatPostDate(post.publishedAt, locale)}</time>
            <h3>{post.title[locale]}</h3>
            <p>{post.excerpt[locale]}</p>
            <Link
              href={localizedPath(`/insights/${post.slug}`, locale)}
              aria-label={`${locale === "id" ? "Baca insight" : "Read insight"}: ${post.title[locale]}`}
            >
              {locale === "id" ? "Baca insight" : "Read insight"} →
            </Link>
          </article>
        ))}
      </div>

      {!visiblePosts.length ? (
        <p className="empty-note">{locale === "id" ? "Belum ada artikel untuk tahun ini." : "No articles for this year yet."}</p>
      ) : null}

      {pageCount > 1 ? (
        <nav className="insight-pagination" aria-label={locale === "id" ? "Navigasi halaman artikel" : "Article pagination"}>
          <button disabled={page === 1} onClick={() => setPage((value) => Math.max(1, value - 1))} type="button">
            {locale === "id" ? "Sebelumnya" : "Previous"}
          </button>
          <span>
            {locale === "id" ? "Halaman" : "Page"} {page} / {pageCount}
          </span>
          <button disabled={page === pageCount} onClick={() => setPage((value) => Math.min(pageCount, value + 1))} type="button">
            {locale === "id" ? "Berikutnya" : "Next"}
          </button>
        </nav>
      ) : null}
    </div>
  );
}

function getPostYear(post: BlogPost) {
  if (!post.publishedAt) return "";
  return new Date(post.publishedAt).getFullYear().toString();
}

function formatPostDate(date: string, locale: Locale) {
  if (!date) return "";
  return new Intl.DateTimeFormat(locale === "id" ? "id-ID" : "en-US", {
    day: "numeric",
    month: "short",
    year: "numeric"
  }).format(new Date(date));
}
