import { Activity } from "lucide-react";
import { prisma } from "@/lib/db";
import { requireAdmin } from "@/lib/admin-guard";

export const dynamic = "force-dynamic";

const PAGE_SIZE = 50;

type Props = { searchParams: Promise<{ page?: string; action?: string }> };

export default async function AdminAuditLog({ searchParams }: Props) {
  await requireAdmin();
  const sp = await searchParams;
  const page = Math.max(1, parseInt(sp.page ?? "1", 10) || 1);
  const action = sp.action ?? "";

  const where = action ? { action: { startsWith: action } } : {};
  const [logs, total] = await Promise.all([
    prisma.auditLog.findMany({
      where,
      orderBy: { createdAt: "desc" },
      skip: (page - 1) * PAGE_SIZE,
      take: PAGE_SIZE,
    }),
    prisma.auditLog.count({ where }),
  ]);
  const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));

  return (
    <div>
      <div className="mb-6">
        <h1 className="font-display text-ink-primary text-2xl font-semibold lg:text-3xl">
          Audit Log
        </h1>
        <p className="text-ink-secondary mt-1 text-sm">
          Mọi thay đổi từ Admin CP — không thể chỉnh sửa, chỉ xem.
        </p>
      </div>

      <form
        method="GET"
        className="border-stroke-subtle bg-bg-elevated/40 mb-4 flex flex-wrap items-end gap-3 rounded-xl border p-4"
      >
        <div>
          <label className="text-ink-muted block text-xs">Lọc action</label>
          <select
            name="action"
            defaultValue={action}
            className="bg-bg-inset border-stroke-default text-ink-primary focus:border-brand-gold mt-1 rounded-md border px-3 py-2 text-sm focus:outline-none"
          >
            <option value="">Tất cả</option>
            <option value="setting">setting.* (cấu hình)</option>
            <option value="user">user.* (user mgmt)</option>
          </select>
        </div>
        <button
          type="submit"
          className="bg-brand-gold text-bg-base rounded-md px-4 py-2 text-sm font-medium"
        >
          Lọc
        </button>
      </form>

      <div className="border-stroke-subtle bg-bg-elevated/40 overflow-hidden rounded-xl border">
        {logs.length === 0 ? (
          <div className="text-ink-muted p-8 text-center text-sm">Không có log.</div>
        ) : (
          <ul className="divide-stroke-subtle/50 divide-y">
            {logs.map((l) => (
              <li key={l.id} className="flex items-start gap-3 px-4 py-3 text-sm">
                <Activity className="text-brand-gold/60 mt-0.5 h-4 w-4 shrink-0" />
                <div className="min-w-0 flex-1">
                  <div className="text-ink-primary">
                    <span className="font-medium">{l.actorName}</span>{" "}
                    <span className="text-ink-secondary">{l.action}</span>
                    {l.target ? <span className="text-ink-muted"> → {l.target}</span> : null}
                  </div>
                  {l.metadata ? (
                    <pre className="text-ink-muted mt-1 max-h-40 overflow-auto text-[11px] break-all whitespace-pre-wrap">
                      {JSON.stringify(l.metadata, null, 2)}
                    </pre>
                  ) : null}
                  <div className="text-ink-muted mt-1 text-[11px]">
                    {l.createdAt.toLocaleString("vi-VN")}
                    {l.ipAddress ? ` · ${l.ipAddress}` : ""}
                  </div>
                </div>
              </li>
            ))}
          </ul>
        )}
      </div>

      {totalPages > 1 ? (
        <div className="mt-4 flex items-center justify-between text-xs">
          <span className="text-ink-muted">
            Trang {page}/{totalPages} · {total} entries
          </span>
          <div className="flex gap-2">
            {page > 1 ? (
              <a
                href={`/admin/audit?action=${action}&page=${page - 1}`}
                className="border-stroke-default text-ink-secondary hover:border-brand-gold/50 rounded-md border px-3 py-1.5"
              >
                ← Trước
              </a>
            ) : null}
            {page < totalPages ? (
              <a
                href={`/admin/audit?action=${action}&page=${page + 1}`}
                className="border-stroke-default text-ink-secondary hover:border-brand-gold/50 rounded-md border px-3 py-1.5"
              >
                Sau →
              </a>
            ) : null}
          </div>
        </div>
      ) : null}
    </div>
  );
}
