import Link from "next/link";
import { Plus } from "lucide-react";
import { adminFetch, requireAdminUser } from "@/lib/adminApi";
import { formatDateTime } from "@/lib/adminLabels";

export const metadata = { title: "Artículos" };

type Row = { id: number; slug: string; titleEs: string; category: string; status: string; publishedAt: string | null; isSample: boolean; updatedAt: string };

export default async function ArticlesAdmin() {
  await requireAdminUser(["admin", "editor"]);
  const { data } = await adminFetch<{ items: Row[] }>("/v1/admin/articles");
  return (
    <div className="max-w-6xl">
      <div className="flex flex-wrap items-end justify-between gap-4">
        <h1 className="font-serif text-4xl">Artículos</h1>
        <Link href="/admin/articles/new" className="flex items-center gap-2 bg-ink px-4 py-2 text-sm text-cream hover:bg-forest">
          <Plus size={15} /> Nuevo artículo
        </Link>
      </div>
      <ul className="mt-8 divide-y divide-ink/10 border border-ink/10 bg-white">
        {data?.items.map((a) => (
          <li key={a.id} className="flex flex-wrap items-center justify-between gap-3 px-5 py-4 text-sm">
            <Link href={`/admin/articles/${a.id}`} className="font-medium hover:text-forest">
              {a.titleEs}
            </Link>
            <span className="flex items-center gap-3 text-stone">
              {a.isSample && <span className="rounded-full bg-sand px-2.5 py-1 text-xs text-ink">Ejemplo</span>}
              <span className={`rounded-full px-2.5 py-1 text-xs ${a.status === "published" ? "bg-forest/15 text-forest" : "bg-ink/10"}`}>
                {a.status === "published" ? "Publicado" : "Borrador"}
              </span>
              {formatDateTime(a.publishedAt ?? a.updatedAt)}
            </span>
          </li>
        ))}
      </ul>
    </div>
  );
}
