import Link from 'next/link';
import { prisma } from '@/lib/prisma';
import { AdminDeleteButton } from '@/components/admin/delete-button';
import type { Locale } from '@/i18n/config';

export default async function AdminBlogPage({ params: { locale } }: { params: { locale: Locale } }) {
  const posts = await prisma.post.findMany({
    orderBy: { createdAt: 'desc' },
    include: { translations: { where: { locale: 'fr' } }, author: { include: { translations: { where: { locale: 'fr' } } } } }
  });

  return (
    <div>
      <div className="flex items-center justify-between">
        <h1 className="font-display text-2xl font-semibold">Blog</h1>
        <div className="flex gap-2">
          <Link href={`/${locale}/admin/authors`} className="rounded-full border border-graphite-800/20 px-4 py-2 text-sm font-semibold">
            Auteurs
          </Link>
          <Link href={`/${locale}/admin/tags`} className="rounded-full border border-graphite-800/20 px-4 py-2 text-sm font-semibold">
            Tags
          </Link>
          <Link
            href={`/${locale}/admin/blog/new`}
            className="rounded-full bg-copper-500 px-4 py-2 text-sm font-semibold text-graphite-950"
          >
            + Nouvel article
          </Link>
        </div>
      </div>

      <div className="mt-6 overflow-hidden rounded-2xl bg-white">
        <table className="w-full text-sm">
          <thead className="border-b border-graphite-800/10 text-graphite-900/50">
            <tr>
              <th className="px-4 py-3 text-start">Titre</th>
              <th className="px-4 py-3 text-start">Auteur</th>
              <th className="px-4 py-3 text-start">Publié</th>
              <th className="px-4 py-3" />
            </tr>
          </thead>
          <tbody>
            {posts.map((p) => (
              <tr key={p.id} className="border-b border-graphite-800/5 last:border-0">
                <td className="px-4 py-3">{p.translations[0]?.title ?? p.slug}</td>
                <td className="px-4 py-3 text-graphite-900/60">{p.author.translations[0]?.name ?? '—'}</td>
                <td className="px-4 py-3">{p.published ? 'Oui' : 'Non'}</td>
                <td className="px-4 py-3 text-end">
                  <Link href={`/${locale}/admin/blog/${p.id}`} className="text-copper-600 hover:underline">
                    Modifier
                  </Link>
                  <AdminDeleteButton apiPath={`/api/admin/posts/${p.id}`} confirmMessage="Supprimer cet article ?" />
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        {posts.length === 0 && (
          <p className="p-6 text-graphite-900/50">
            Aucun article. Créez d'abord un auteur si ce n'est pas déjà fait.
          </p>
        )}
      </div>
    </div>
  );
}
