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

export const dynamic = "force-dynamic";

const ACTION_COLORS: Record<string, string> = {
  create: "text-emerald-300",
  publish: "text-emerald-300",
  update: "text-sky-300",
  unpublish: "text-amber-300",
  revoke: "text-rose-300",
  delete: "text-rose-300",
};

const SOURCE_BADGES: Record<string, string> = {
  admin: "bg-sky-500/15 text-sky-300",
  api: "bg-violet-500/15 text-violet-300",
  system: "bg-zinc-500/15 text-zinc-300",
};

function fmtDate(d: Date): string {
  return new Intl.DateTimeFormat("vi-VN", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  }).format(d);
}

function actionColor(action: string): string {
  const verb = action.split(".").pop() ?? action;
  return ACTION_COLORS[verb] ?? "text-ink-secondary";
}

const PAGE_SIZE = 50;

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

  const where = {
    ...(source ? { source } : {}),
    ...(actionFilter ? { action: { contains: actionFilter } } : {}),
    ...(actor
      ? {
          OR: [
            { actorName: { contains: actor, mode: "insensitive" as const } },
            { actorEmail: { contains: actor, mode: "insensitive" as const } },
          ],
        }
      : {}),
  };

  const [total, logs, distinctActions] = await Promise.all([
    prisma.auditLog.count({ where }),
    prisma.auditLog.findMany({
      where,
      orderBy: { createdAt: "desc" },
      skip: (page - 1) * PAGE_SIZE,
      take: PAGE_SIZE,
    }),
    prisma.auditLog.findMany({
      distinct: ["action"],
      select: { action: true },
      take: 50,
      orderBy: { createdAt: "desc" },
    }),
  ]);

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

  function buildHref(p: number): string {
    const params = new URLSearchParams();
    if (source) params.set("source", source);
    if (actionFilter) params.set("action", actionFilter);
    if (actor) params.set("actor", actor);
    if (p !== 1) params.set("page", String(p));
    const s = params.toString();
    return s ? `/admin/audit?${s}` : "/admin/audit";
  }

  return (
    <div>
      <div className="mb-6">
        <h1 className="font-display text-2xl lg:text-3xl font-bold mb-1">Audit Log</h1>
        <p className="text-sm text-ink-muted">
          Toàn bộ hành động ghi nhận trên hệ thống — admin actions, API calls, system events.
        </p>
      </div>

      <form className="flex flex-wrap gap-2 mb-5" method="get">
        <input
          type="search"
          name="actor"
          defaultValue={actor}
          placeholder="Tác nhân (tên/email)…"
          className="flex-1 min-w-[200px] px-3 py-2 rounded-lg bg-bg-elevated border border-stroke-subtle text-sm"
        />
        <input
          type="search"
          name="action"
          defaultValue={actionFilter}
          placeholder="Action (vd: article.publish)…"
          className="flex-1 min-w-[200px] px-3 py-2 rounded-lg bg-bg-elevated border border-stroke-subtle text-sm"
          list="action-list"
        />
        <datalist id="action-list">
          {distinctActions.map((a) => (
            <option key={a.action} value={a.action} />
          ))}
        </datalist>
        <select
          name="source"
          defaultValue={source}
          className="px-3 py-2 rounded-lg bg-bg-elevated border border-stroke-subtle text-sm"
        >
          <option value="">Mọi nguồn</option>
          <option value="admin">Admin</option>
          <option value="api">API</option>
          <option value="system">System</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>

      <div className="text-xs text-ink-muted mb-3">
        {total.toLocaleString("vi-VN")} bản ghi · trang {page}/{totalPages}
      </div>

      {logs.length === 0 ? (
        <div className="rounded-xl border border-stroke-subtle bg-bg-elevated/40 p-8 text-center text-sm text-ink-muted">
          Không có bản ghi nào khớp.
        </div>
      ) : (
        <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">Thời gian</th>
                <th className="px-4 py-2.5 font-medium text-ink-muted">Nguồn</th>
                <th className="px-4 py-2.5 font-medium text-ink-muted">Tác nhân</th>
                <th className="px-4 py-2.5 font-medium text-ink-muted">Action</th>
                <th className="px-4 py-2.5 font-medium text-ink-muted">Target</th>
                <th className="px-4 py-2.5 font-medium text-ink-muted">Meta</th>
              </tr>
            </thead>
            <tbody>
              {logs.map((log) => {
                const sb = SOURCE_BADGES[log.source] ?? SOURCE_BADGES.system;
                return (
                  <tr
                    key={log.id}
                    className="border-b border-stroke-subtle/60 last:border-0 hover:bg-bg-elevated/30 transition"
                  >
                    <td className="px-4 py-3 whitespace-nowrap text-xs font-mono text-ink-muted">
                      {fmtDate(log.createdAt)}
                    </td>
                    <td className="px-4 py-3">
                      <span className={`text-xs px-2 py-0.5 rounded-full ${sb}`}>
                        {log.source}
                      </span>
                    </td>
                    <td className="px-4 py-3">
                      {log.actorName ? (
                        <>
                          <div className="text-xs font-medium">{log.actorName}</div>
                          {log.actorEmail && (
                            <div className="text-[11px] text-ink-muted">{log.actorEmail}</div>
                          )}
                        </>
                      ) : log.tokenPrefix ? (
                        <code className="text-xs font-mono text-ink-muted">{log.tokenPrefix}…</code>
                      ) : (
                        <span className="text-ink-muted text-xs">—</span>
                      )}
                    </td>
                    <td className="px-4 py-3">
                      <code className={`text-xs font-mono ${actionColor(log.action)}`}>
                        {log.action}
                      </code>
                    </td>
                    <td className="px-4 py-3">
                      {log.target ? (
                        <code className="text-[11px] font-mono text-ink-muted">
                          {log.target.slice(0, 18)}
                          {log.target.length > 18 ? "…" : ""}
                        </code>
                      ) : (
                        <span className="text-ink-muted text-xs">—</span>
                      )}
                    </td>
                    <td className="px-4 py-3 max-w-[280px]">
                      {log.meta ? (
                        <details className="text-xs">
                          <summary className="cursor-pointer text-ink-muted hover:text-ink-primary">
                            xem
                          </summary>
                          <pre className="mt-1 px-2 py-1.5 rounded bg-bg-overlay text-[11px] overflow-x-auto whitespace-pre-wrap">
                            {JSON.stringify(log.meta, null, 2)}
                          </pre>
                        </details>
                      ) : (
                        <span className="text-ink-muted text-xs">—</span>
                      )}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}

      {totalPages > 1 && (
        <div className="flex items-center justify-between mt-5 text-sm">
          <Link
            href={buildHref(Math.max(1, 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={buildHref(Math.min(totalPages, 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>
  );
}
