import { prisma } from "@/lib/db";
import { loadAiConfig } from "@/lib/ai/openai";
import {
  PromptStudio,
  ProviderPing,
  MetaGenerator,
  type ArticleOption,
} from "./_form";

export const dynamic = "force-dynamic";

export default async function AiAdminPage() {
  const cfg = await loadAiConfig();

  const articles = await prisma.article.findMany({
    where: { status: "published" },
    orderBy: { publishedAt: "desc" },
    take: 100,
    select: {
      id: true,
      title: true,
      slug: true,
      metaTitle: true,
      metaDesc: true,
    },
  });
  const opts: ArticleOption[] = articles.map((a) => ({
    id: a.id,
    title: a.title,
    slug: a.slug,
    hasMeta: !!(a.metaTitle && a.metaDesc),
  }));

  return (
    <div>
      <div className="mb-6">
        <h1 className="font-display text-2xl lg:text-3xl font-bold mb-1">AI Writer</h1>
        <p className="text-sm text-ink-muted">
          Test prompt, sinh meta tự động, hỗ trợ viết bài. AI provider cấu hình ở{" "}
          <a href="/admin/settings" className="text-accent-primary hover:underline">
            /admin/settings
          </a>
          .
        </p>
      </div>

      <div className="rounded-xl border border-stroke-subtle bg-bg-elevated/40 p-4 mb-6">
        <div className="flex items-center justify-between flex-wrap gap-3">
          <div>
            <div className="text-xs text-ink-muted">Provider hiện tại</div>
            {cfg ? (
              <div className="text-sm mt-0.5">
                <code className="font-mono text-accent-primary">{cfg.model}</code>{" "}
                <span className="text-ink-muted">@</span>{" "}
                <code className="font-mono text-ink-secondary text-xs">
                  {cfg.baseUrl}
                </code>
              </div>
            ) : (
              <div className="text-sm text-amber-300 mt-0.5">
                Chưa cấu hình. Mở /admin/settings.
              </div>
            )}
          </div>
          {cfg && <ProviderPing />}
        </div>
      </div>

      <div className="grid lg:grid-cols-2 gap-6">
        <PromptStudio />
        <MetaGenerator articles={opts} />
      </div>
    </div>
  );
}
