import Link from "next/link";
import { prisma } from "@/lib/db";
import { ArticlesTable, type ArticleRow, type CategoryOption } from "./_table";

export const dynamic = "force-dynamic";

export default async function ArticlesAdminPage({
  searchParams,
}: {
  searchParams: Promise<{ q?: string; status?: string }>;
}) {
  const sp = await searchParams;
  const q = (sp.q ?? "").trim();
  const status = (sp.status ?? "").trim();

  const [articles, cats] = await Promise.all([
    prisma.article.findMany({
      where: {
        AND: [
          q
            ? {
                OR: [
                  { title: { contains: q, mode: "insensitive" } },
                  { slug: { contains: q, mode: "insensitive" } },
                ],
              }
            : {},
          status ? { status } : {},
        ],
      },
      orderBy: { updatedAt: "desc" },
      take: 200,
      select: {
        id: true,
        slug: true,
        title: true,
        status: true,
        publishedAt: true,
        scheduledFor: true,
        updatedAt: true,
        seoScore: true,
        viewCount: true,
        author: { select: { name: true } },
        category: { select: { name: true, slug: true } },
      },
    }),
    prisma.category.findMany({
      orderBy: { name: "asc" },
      select: { slug: true, name: true },
    }),
  ]);

  const rows: ArticleRow[] = articles.map((a) => ({
    id: a.id,
    slug: a.slug,
    title: a.title,
    status: a.status,
    publishedAt: a.publishedAt,
    scheduledFor: a.scheduledFor,
    updatedAt: a.updatedAt,
    seoScore: a.seoScore,
    viewCount: a.viewCount,
    authorName: a.author.name,
    categoryName: a.category?.name ?? null,
    categorySlug: a.category?.slug ?? null,
  }));
  const catOpts: CategoryOption[] = cats.map((c) => ({ slug: c.slug, name: c.name }));

  return (
    <div>
      <div className="flex items-start justify-between gap-4 mb-6">
        <div>
          <h1 className="font-display text-2xl lg:text-3xl font-bold mb-1">Bài viết</h1>
          <p className="text-sm text-ink-muted">
            Quản lý nội dung — tạo, sửa, xuất bản hoặc gỡ bài. Chọn nhiều bài để hành động hàng loạt.
          </p>
        </div>
        <Link
          href="/admin/articles/new"
          className="inline-flex items-center gap-1.5 px-4 py-2 rounded-lg bg-accent-primary text-white text-sm font-medium hover:bg-accent-primary/90 transition shrink-0"
        >
          + Bài mới
        </Link>
      </div>

      <form className="flex flex-wrap gap-2 mb-5" method="get">
        <input
          type="search"
          name="q"
          defaultValue={q}
          placeholder="Tìm theo tiêu đề / slug…"
          className="flex-1 min-w-[220px] px-3 py-2 rounded-lg bg-bg-elevated border border-stroke-subtle text-sm focus:outline-none focus:border-accent-primary"
        />
        <select
          name="status"
          defaultValue={status}
          className="px-3 py-2 rounded-lg bg-bg-elevated border border-stroke-subtle text-sm focus:outline-none focus:border-accent-primary"
        >
          <option value="">Tất cả trạng thái</option>
          <option value="draft">Nháp</option>
          <option value="published">Đã đăng</option>
          <option value="scheduled">Hẹn giờ</option>
          <option value="archived">Lưu trữ</option>
        </select>
        <button
          type="submit"
          className="px-4 py-2 rounded-lg bg-bg-elevated border border-stroke-subtle text-sm hover:border-accent-primary transition"
        >
          Lọc
        </button>
      </form>

      {rows.length === 0 ? (
        <div className="rounded-xl border border-stroke-subtle bg-bg-elevated/40 p-8 text-center">
          <p className="text-ink-muted text-sm mb-3">Chưa có bài viết nào khớp.</p>
          <Link
            href="/admin/articles/new"
            className="text-accent-primary text-sm font-medium hover:underline"
          >
            Tạo bài đầu tiên →
          </Link>
        </div>
      ) : (
        <ArticlesTable rows={rows} categories={catOpts} />
      )}
    </div>
  );
}
