import Link from "next/link";
import { desc, eq, sql } from "drizzle-orm";
import { db } from "@/db";
import { auditLog, users } from "@/db/schema";
import { requirePlatformAdmin } from "@/lib/auth/guards";
import { de } from "@/lib/i18n/de";
import { DataTable } from "@/components/admin/DataTable";
import { paginationSchema } from "@/lib/validation/common";

export const metadata = { title: "Audit-Log — Administration" };

const dtf = new Intl.DateTimeFormat("de-AT", {
  dateStyle: "short",
  timeStyle: "short",
});

export default async function AuditPage({
  searchParams,
}: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  await requirePlatformAdmin();
  const sp = await searchParams;

  const aktionFilter =
    typeof sp.aktion === "string" && sp.aktion.trim() ? sp.aktion.trim() : null;
  const { page, pageSize } = paginationSchema.parse({
    page: sp.page,
    pageSize: 25,
  });

  const whereClause = aktionFilter
    ? eq(auditLog.aktion, aktionFilter)
    : undefined;

  const rows = await db
    .select({
      id: auditLog.id,
      zeitpunkt: auditLog.zeitpunkt,
      aktion: auditLog.aktion,
      zielTyp: auditLog.zielTyp,
      zielId: auditLog.zielId,
      actorName: users.name,
    })
    .from(auditLog)
    .leftJoin(users, eq(users.id, auditLog.actorUserId))
    .where(whereClause)
    .orderBy(desc(auditLog.zeitpunkt))
    .limit(pageSize)
    .offset((page - 1) * pageSize);

  const totalRows = await db
    .select({ total: sql<number>`count(*)::int` })
    .from(auditLog)
    .where(whereClause);
  const total = totalRows[0]?.total ?? 0;

  const aktionen = await db
    .selectDistinct({ aktion: auditLog.aktion })
    .from(auditLog)
    .orderBy(auditLog.aktion);

  const totalPages = Math.max(1, Math.ceil((total ?? 0) / pageSize));
  const qp = (p: number) =>
    `?page=${p}${aktionFilter ? `&aktion=${encodeURIComponent(aktionFilter)}` : ""}`;

  return (
    <div className="space-y-4">
      <h1 className="font-display text-2xl text-navy">{de.admin.navAudit}</h1>

      <form className="flex items-end gap-2" action="/admin/audit" method="get">
        <label className="text-sm">
          <span className="mb-1 block font-medium text-anthrazit/70">
            {de.admin.auditFilter}
          </span>
          <select
            name="aktion"
            defaultValue={aktionFilter ?? ""}
            className="h-9 rounded border border-rand bg-white px-2 text-sm text-anthrazit focus:outline-none focus:ring-2 focus:ring-navy"
          >
            <option value="">– alle –</option>
            {aktionen.map((a) => (
              <option key={a.aktion} value={a.aktion}>
                {a.aktion}
              </option>
            ))}
          </select>
        </label>
        <button
          type="submit"
          className="h-9 rounded bg-navy px-3 text-sm font-medium text-white hover:bg-navy/90"
        >
          {de.search.filter}
        </button>
      </form>

      <DataTable
        rows={rows}
        getRowKey={(r) => r.id}
        columns={[
          {
            key: "zeitpunkt",
            header: de.admin.auditZeitpunkt,
            render: (r) => (
              <span className="tabular-nums text-anthrazit/70">
                {dtf.format(new Date(r.zeitpunkt))}
              </span>
            ),
          },
          {
            key: "aktion",
            header: de.admin.auditAktion,
            render: (r) => (
              <span className="font-medium text-anthrazit">{r.aktion}</span>
            ),
          },
          {
            key: "ziel",
            header: de.admin.auditZiel,
            render: (r) => r.zielTyp ?? "–",
          },
          {
            key: "akteur",
            header: de.admin.auditAkteur,
            render: (r) => r.actorName ?? "–",
          },
        ]}
      />

      <div className="flex items-center justify-between text-sm text-anthrazit/70">
        <span>{total} Einträge</span>
        <div className="flex gap-2">
          {page > 1 && (
            <Link href={qp(page - 1)} className="text-navy hover:underline">
              ← {de.admin.zurueck}
            </Link>
          )}
          <span>
            {page} / {totalPages}
          </span>
          {page < totalPages && (
            <Link href={qp(page + 1)} className="text-navy hover:underline">
              {de.admin.weiter} →
            </Link>
          )}
        </div>
      </div>
    </div>
  );
}
