import Link from "next/link";
import { createAdminClient } from "@/lib/supabase/admin";

export const dynamic = "force-dynamic";
export const revalidate = 0;

interface RewriteRow {
  id: string;
  slug: string;
  title: string;
  excerpt: string;
  category: string;
  tags: string[];
  status: string;
  created_at: string;
  persona_id: string;
  original_submission_id: string;
}

interface PersonaRow {
  id: string;
  slug: string;
  name: string;
  avatar_url: string | null;
  beat: string | null;
}

async function loadQueue() {
  const sb = createAdminClient();
  const { data: rewrites } = await sb
    .from("ai_rewritten_articles")
    .select("id, slug, title, excerpt, category, tags, status, created_at, persona_id, original_submission_id")
    .eq("status", "ai_rewritten_pending_review")
    .order("created_at", { ascending: false })
    .limit(50);

  const { data: personas } = await sb
    .from("ai_personas")
    .select("id, slug, name, avatar_url, beat");

  const personaById = new Map<string, PersonaRow>();
  for (const p of (personas || []) as PersonaRow[]) personaById.set(p.id, p);

  return {
    rewrites: (rewrites || []) as RewriteRow[],
    personaById,
  };
}

export default async function ReviewQueuePage() {
  const { rewrites, personaById } = await loadQueue();

  return (
    <main className="mx-auto max-w-5xl px-6 py-10 text-[#e5e7eb]">
      <header className="mb-8 border-b border-[#222] pb-4">
        <h1 className="text-3xl font-bold tracking-tight">AI Review Queue</h1>
        <p className="mt-2 text-sm text-[#9ca3af]">
          AI-rewritten articles pending editor approval. {rewrites.length} pending.
        </p>
      </header>

      {rewrites.length === 0 ? (
        <div className="rounded border border-[#1f2937] bg-[#0b0f17] p-8 text-center text-[#9ca3af]">
          No rewrites in the queue.
        </div>
      ) : (
        <ul className="space-y-4">
          {rewrites.map((r) => {
            const persona = personaById.get(r.persona_id);
            return (
              <li
                key={r.id}
                className="rounded border border-[#1f2937] bg-[#0b0f17] p-5 hover:border-[#1D4ED8] transition-colors"
              >
                <div className="flex items-start gap-4">
                  {persona?.avatar_url ? (
                    <img
                      src={persona.avatar_url}
                      alt={persona.name}
                      width={56}
                      height={56}
                      className="rounded-full border border-[#1f2937]"
                    />
                  ) : (
                    <div className="h-14 w-14 rounded-full bg-[#1f2937]" />
                  )}
                  <div className="flex-1 min-w-0">
                    <div className="text-xs uppercase tracking-wider text-[#1D4ED8]">
                      {persona?.name || "—"} · {r.category}
                    </div>
                    <h2 className="text-xl font-semibold mt-1">{r.title}</h2>
                    <p className="text-sm text-[#9ca3af] mt-1 line-clamp-2">{r.excerpt}</p>
                    <div className="mt-3 flex flex-wrap gap-2 text-xs">
                      {(r.tags || []).map((t) => (
                        <span key={t} className="rounded bg-[#1f2937] px-2 py-0.5">
                          {t}
                        </span>
                      ))}
                    </div>
                    <div className="mt-4 flex flex-wrap items-center gap-3 text-xs">
                      <Link
                        href={`/admin/review-queue/${r.id}`}
                        className="rounded bg-[#1d4ed8] px-3 py-1.5 font-medium text-white hover:bg-[#1E3A8A]"
                      >
                        Review
                      </Link>
                      <span className="text-[#6b7280]">
                        Submitted {new Date(r.created_at).toLocaleString()}
                      </span>
                    </div>
                  </div>
                </div>
              </li>
            );
          })}
        </ul>
      )}
    </main>
  );
}
