import Link from "next/link";
import { prisma } from "@/lib/db";

export const dynamic = "force-dynamic";

export default async function AdminPage() {
  const decisions = await getDecisions();

  return (
    <main className="min-h-screen bg-[#f4efe6] px-4 py-6 text-stone-950 sm:px-6">
      <div className="mx-auto max-w-7xl">
        <header className="mb-6 flex flex-wrap items-end justify-between gap-4">
          <div>
            <p className="text-xs font-semibold uppercase tracking-[.18em] text-teal-800">Admin Center</p>
            <h1 className="text-3xl font-semibold tracking-normal">KI-Moderation</h1>
          </div>
          <Link className="rounded-md border border-stone-300 bg-white px-3 py-2 text-sm font-semibold" href="/">
            Zurueck
          </Link>
        </header>

        <section className="overflow-hidden rounded-lg border border-stone-300 bg-white shadow-sm">
          <div className="grid grid-cols-[1.2fr_.7fr_.6fr_.7fr] border-b border-stone-300 bg-stone-100 px-4 py-3 text-xs font-semibold uppercase tracking-[.12em] text-stone-600">
            <span>Beitrag</span>
            <span>Entscheidung</span>
            <span>Vertrauen</span>
            <span>Zeitpunkt</span>
          </div>
          {decisions.length === 0 ? (
            <div className="p-6 text-sm text-stone-600">Noch keine Moderationsentscheidungen vorhanden.</div>
          ) : (
            <div className="divide-y divide-stone-200">
              {decisions.map((decision) => (
                <article key={decision.id} className="grid gap-3 px-4 py-4 text-sm md:grid-cols-[1.2fr_.7fr_.6fr_.7fr]">
                  <div>
                    <h2 className="font-semibold">{decision.contribution.title}</h2>
                    <p className="mt-1 line-clamp-2 text-stone-600">{decision.reasoning}</p>
                  </div>
                  <span className="font-semibold">{decision.outcome}</span>
                  <span>{Math.round(decision.confidence * 100)}%</span>
                  <time className="text-stone-600">{decision.createdAt.toLocaleString("de-DE")}</time>
                </article>
              ))}
            </div>
          )}
        </section>
      </div>
    </main>
  );
}

async function getDecisions() {
  try {
    return await prisma.moderationDecision.findMany({
      include: {
        contribution: true,
      },
      orderBy: {
        createdAt: "desc",
      },
      take: 30,
    });
  } catch {
    return [];
  }
}
