import type { Metadata } from "next";
import Link from "next/link";
import { PageHero } from "@/components/PageHero";
import { Unavailable } from "@/components/RichText";
import { ApiDown, api } from "@/lib/api";
import type { ArticleCard } from "@/lib/types";

export const metadata: Metadata = {
  title: "دانش و تحلیل",
  description: "یادداشت‌های تخصصی درباره اعتبار مالیاتی، نوآوری، هوش مصنوعی صنعتی و تأمین مالی نوآوری.",
};

type Props = { searchParams: Promise<{ q?: string; category?: string }> };

export default async function InsightsPage({ searchParams }: Props) {
  try {
    const query = await searchParams;
    const params = new URLSearchParams();
    if (query.q) params.set("q", query.q);
    if (query.category) params.set("category", query.category);
    const payload = await api<{ categories: { slug: string; name: string }[]; articles: ArticleCard[] }>(`/articles${params.size ? `?${params}` : ""}`);

    const chip = (active: boolean) =>
      `relative px-1 pb-3 text-base font-semibold transition ${active ? "text-navy after:absolute after:inset-x-0 after:bottom-0 after:h-0.5 after:bg-gradient-to-l after:from-gold after:to-teal" : "text-muted hover:text-navy"}`;

    return (
      <>
        <PageHero title="دانش و تحلیل" lead="یادداشت‌های قابل ویرایش برای اعتبار تخصصی و دیده شدن در جست‌وجو." />
        <div className="shell section-pad">
          <form className="form-shell grid gap-4 md:grid-cols-[1fr_auto] md:items-end" action="/insights">
            <label className="block text-base font-medium text-muted">جست‌وجو
              <input name="q" defaultValue={query.q ?? ""} className="field mt-2" placeholder="عبارت کلیدی..." />
            </label>
            <button className="btn btn-solid">جست‌وجو</button>
          </form>
          <div className="mt-8 flex flex-wrap gap-x-6 gap-y-3 border-b border-line">
            <Link href="/insights" className={chip(!query.category)}>همه دسته‌ها</Link>
            {payload.categories.map((category) => (
              <Link key={category.slug} href={`/insights?category=${category.slug}`} className={chip(query.category === category.slug)}>
                {category.name}
              </Link>
            ))}
          </div>
          {payload.articles.length === 0 ? (
            <p className="mt-10 text-[1.05rem] text-muted">مطلبی با این عبارت پیدا نشد.</p>
          ) : (
            <div className="mt-8 grid gap-4">
              {payload.articles.map((article) => (
                <article key={article.slug} className="panel grid gap-4 p-7 pe-6 ps-8 md:grid-cols-[0.8fr_1.2fr]">
                  <span className="panel-accent" aria-hidden="true" />
                  <div>
                    <p className="text-sm font-semibold tracking-[0.14em] text-teal">{article.category?.name}</p>
                    <h2 className="mt-3 text-[1.25rem] font-extrabold text-navy">
                      <Link href={`/insights/${article.slug}`} className="hover:text-teal">{article.title}</Link>
                    </h2>
                    <p className="mt-3 text-[0.95rem] text-muted">{article.published_at_jalali} · {article.author_name}</p>
                  </div>
                  <p className="text-[1.05rem] leading-9 text-muted">{article.excerpt}</p>
                </article>
              ))}
            </div>
          )}
        </div>
      </>
    );
  } catch (error) {
    if (error instanceof ApiDown) return <Unavailable />;
    throw error;
  }
}
