import { prisma } from "@/lib/db";
import { RedirectCreateForm, RedirectRow } from "./_form";

export const dynamic = "force-dynamic";

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

  const redirects = await prisma.redirect.findMany({
    where: q
      ? {
          OR: [
            { fromPath: { contains: q, mode: "insensitive" } },
            { toPath: { contains: q, mode: "insensitive" } },
          ],
        }
      : undefined,
    orderBy: [{ enabled: "desc" }, { createdAt: "desc" }],
    take: 200,
  });

  return (
    <div>
      <div className="mb-6">
        <h1 className="font-display text-2xl lg:text-3xl font-bold mb-1">Redirect 301/302</h1>
        <p className="text-sm text-ink-muted">
          Map URL cũ sang URL mới. Hữu ích cho migration WordPress → CMS, đổi slug, hoặc gộp bài.
          From/To phải là path tương đối (bắt đầu bằng <code className="text-xs px-1 rounded bg-bg-overlay">/</code>) hoặc absolute URL.
        </p>
      </div>

      <RedirectCreateForm />

      <form className="flex gap-2 mb-4" method="get">
        <input
          type="search"
          name="q"
          defaultValue={q}
          placeholder="Tìm theo from/to…"
          className="flex-1 px-3 py-2 rounded-lg bg-bg-elevated border border-stroke-subtle text-sm"
        />
        <button
          type="submit"
          className="px-4 py-2 rounded-lg bg-bg-elevated border border-stroke-subtle text-sm hover:border-accent-primary transition"
        >
          Tìm
        </button>
      </form>

      <div className="rounded-xl border border-stroke-subtle overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-bg-elevated/60 text-left">
            <tr className="border-b border-stroke-subtle">
              <th className="px-4 py-2.5 font-medium text-ink-muted">From</th>
              <th className="px-4 py-2.5 font-medium text-ink-muted">To</th>
              <th className="px-4 py-2.5 font-medium text-ink-muted">Status</th>
              <th className="px-4 py-2.5 font-medium text-ink-muted">Hits</th>
              <th className="px-4 py-2.5 font-medium text-ink-muted">TT</th>
              <th className="px-4 py-2.5 font-medium text-ink-muted text-right">Hành động</th>
            </tr>
          </thead>
          <tbody>
            {redirects.length === 0 ? (
              <tr>
                <td colSpan={6} className="px-4 py-8 text-center text-ink-muted text-sm">
                  {q ? "Không tìm thấy redirect khớp." : "Chưa có redirect nào."}
                </td>
              </tr>
            ) : (
              redirects.map((r) => <RedirectRow key={r.id} r={r} />)
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
