import Link from "next/link";
import { prisma } from "@/lib/db";
import { UploadForm, MediaCard, BulkAltButton } from "./_form";

export const dynamic = "force-dynamic";

const PAGE_SIZE = 24;

export default async function MediaAdminPage({
  searchParams,
}: {
  searchParams: Promise<{ page?: string }>;
}) {
  const sp = await searchParams;
  const page = Math.max(1, parseInt(sp.page ?? "1", 10) || 1);

  const [items, total, missingAlt] = await Promise.all([
    prisma.media.findMany({
      orderBy: { createdAt: "desc" },
      skip: (page - 1) * PAGE_SIZE,
      take: PAGE_SIZE,
    }),
    prisma.media.count(),
    prisma.media.count({ where: { OR: [{ alt: null }, { alt: "" }] } }),
  ]);

  const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));

  return (
    <div>
      <div className="mb-6 flex items-start justify-between gap-4">
        <div>
          <h1 className="font-display text-2xl lg:text-3xl font-bold mb-1">Media</h1>
          <p className="text-sm text-ink-muted">
            Thư viện ảnh dùng cho cover bài, ảnh trong thân bài, OG image. Upload tại đây hoặc qua API{" "}
            <code className="text-xs px-1 rounded bg-bg-overlay">POST /api/v1/media</code>.
          </p>
        </div>
        {missingAlt > 0 && (
          <div className="shrink-0">
            <BulkAltButton missingCount={missingAlt} />
          </div>
        )}
      </div>

      <UploadForm />

      <div className="text-xs text-ink-muted mb-3 flex items-center gap-3">
        <span>
          {total.toLocaleString("vi-VN")} file · trang {page}/{totalPages}
        </span>
        {missingAlt > 0 && (
          <span className="text-amber-300">
            ⚠ {missingAlt.toLocaleString("vi-VN")} ảnh chưa có alt text
          </span>
        )}
      </div>

      {items.length === 0 ? (
        <div className="rounded-xl border border-stroke-subtle bg-bg-elevated/40 p-8 text-center text-sm text-ink-muted">
          Chưa có ảnh nào. Upload ở khung phía trên.
        </div>
      ) : (
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4">
          {items.map((m) => (
            <MediaCard key={m.id} m={m} />
          ))}
        </div>
      )}

      {totalPages > 1 && (
        <div className="flex items-center justify-between mt-6 text-sm">
          <Link
            href={page > 1 ? `/admin/media?page=${page - 1}` : "#"}
            className={`px-4 py-2 rounded-lg border border-stroke-subtle hover:border-accent-primary transition ${
              page <= 1 ? "pointer-events-none opacity-40" : ""
            }`}
          >
            ← Trước
          </Link>
          <span className="text-xs text-ink-muted">
            {page} / {totalPages}
          </span>
          <Link
            href={page < totalPages ? `/admin/media?page=${page + 1}` : "#"}
            className={`px-4 py-2 rounded-lg border border-stroke-subtle hover:border-accent-primary transition ${
              page >= totalPages ? "pointer-events-none opacity-40" : ""
            }`}
          >
            Sau →
          </Link>
        </div>
      )}
    </div>
  );
}
