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

export const dynamic = "force-dynamic";

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

  const pages = await prisma.page.findMany({
    where: {
      AND: [
        q
          ? {
              OR: [
                { title: { contains: q, mode: "insensitive" } },
                { slug: { contains: q, mode: "insensitive" } },
              ],
            }
          : {},
        status ? { status } : {},
      ],
    },
    orderBy: { updatedAt: "desc" },
    select: {
      id: true,
      slug: true,
      title: true,
      status: true,
      isSystem: true,
      showInFooter: true,
      footerOrder: true,
      publishedAt: true,
      updatedAt: true,
    },
  });

  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">Trang tĩnh</h1>
          <p className="text-sm text-ink-muted">
            Tự tạo trang nội dung như Giới thiệu, Chính sách, Landing — tách biệt với bài viết tin
            tức. Tổng: {pages.length} trang.
          </p>
        </div>
        <Link
          href="/admin/pages/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"
        >
          + Trang 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>
        </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>

      {pages.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ó trang tĩnh nào.</p>
          <Link
            href="/admin/pages/new"
            className="text-accent-primary text-sm font-medium hover:underline"
          >
            Tạo trang đầu tiên →
          </Link>
        </div>
      ) : (
        <div className="rounded-xl border border-stroke-subtle bg-bg-elevated/40 overflow-hidden">
          <div className="grid grid-cols-12 gap-4 px-4 py-3 text-xs font-medium text-ink-muted uppercase tracking-wider border-b border-stroke-subtle">
            <div className="col-span-5">Tiêu đề</div>
            <div className="col-span-2">Slug</div>
            <div className="col-span-1">Trạng thái</div>
            <div className="col-span-2">Footer</div>
            <div className="col-span-2 text-right">Cập nhật</div>
          </div>
          {pages.map((p) => (
            <Link
              key={p.id}
              href={`/admin/pages/${p.id}`}
              className="grid grid-cols-12 gap-4 px-4 py-3 text-sm hover:bg-bg-overlay transition border-b border-stroke-subtle/50 last:border-0"
            >
              <div className="col-span-5 flex items-center gap-2 min-w-0">
                <span className="font-medium truncate">{p.title}</span>
                {p.isSystem ? (
                  <span className="px-1.5 py-0.5 rounded text-[10px] bg-amber-500/10 text-amber-300 shrink-0">
                    HỆ THỐNG
                  </span>
                ) : null}
              </div>
              <div className="col-span-2 text-ink-muted truncate">/{p.slug}</div>
              <div className="col-span-1">
                <span
                  className={
                    p.status === "published"
                      ? "px-1.5 py-0.5 rounded text-[10px] bg-emerald-500/10 text-emerald-300"
                      : "px-1.5 py-0.5 rounded text-[10px] bg-stone-500/10 text-stone-300"
                  }
                >
                  {p.status === "published" ? "Đăng" : "Nháp"}
                </span>
              </div>
              <div className="col-span-2 text-ink-muted">
                {p.showInFooter ? `✓ thứ tự ${p.footerOrder}` : "—"}
              </div>
              <div className="col-span-2 text-right text-ink-muted text-xs">
                {p.updatedAt.toLocaleString("vi-VN", {
                  day: "2-digit",
                  month: "2-digit",
                  year: "numeric",
                  hour: "2-digit",
                  minute: "2-digit",
                })}
              </div>
            </Link>
          ))}
        </div>
      )}
    </div>
  );
}
