import type { Metadata } from "next";
import Link from "next/link";
import { eq } from "drizzle-orm";
import { ArrowLeft, User as UserIcon, Clock, Link2 } from "lucide-react";
import { notFound } from "next/navigation";
import { requireAdmin } from "@/lib/auth/admin-guard";
import { db } from "@/lib/db/client";
import { adminAudit, users } from "@/lib/db/schema";
import {
  AdminHeading,
  FormSection,
  formatAdminDateTime,
  formatAdminRelative,
} from "@/components/admin";

export const metadata: Metadata = { title: "Audit event" };
export const dynamic = "force-dynamic";

function humaniseAction(action: string): string {
  return action.replace(/_/g, " ").replace(/^./, (c) => c.toUpperCase());
}

function prettyJson(value: unknown): string {
  try {
    return JSON.stringify(value, null, 2);
  } catch {
    return String(value);
  }
}

export default async function AuditEventPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  await requireAdmin();
  const { id } = await params;

  const [row] = await db
    .select({
      event: adminAudit,
      adminName: users.name,
      adminEmail: users.email,
    })
    .from(adminAudit)
    .leftJoin(users, eq(users.id, adminAudit.adminUserId))
    .where(eq(adminAudit.id, id))
    .limit(1);
  if (!row) notFound();

  const meta = row.event.metadata as Record<string, unknown> | null;
  const hasBefore = meta && typeof meta === "object" && "before" in meta;
  const hasAfter = meta && typeof meta === "object" && "after" in meta;

  return (
    <>
      <div className="mb-4">
        <Link
          href="/admin/audit"
          className="inline-flex items-center gap-1 text-[13px] font-semibold text-[var(--color-slate)] hover:text-[var(--color-blue)]"
        >
          <ArrowLeft className="h-3.5 w-3.5" aria-hidden />
          Back to audit log
        </Link>
      </div>

      <AdminHeading
        eyebrow="Audit"
        title={humaniseAction(row.event.action)}
        lede={
          <code className="font-mono text-[12px] text-[var(--color-slate)]">
            {row.event.action}
          </code>
        }
      />

      <div className="grid gap-4 md:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
        <FormSection
          title={hasBefore || hasAfter ? "Before / after" : "Metadata"}
          description="Full metadata payload recorded when this event fired."
        >
          {hasBefore || hasAfter ? (
            <div className="grid gap-4 md:grid-cols-2">
              <div>
                <h4 className="mb-2 text-[11px] font-bold uppercase tracking-wider text-red-700">
                  Before
                </h4>
                <pre className="max-h-[480px] overflow-auto rounded-lg bg-red-50/40 p-3 text-[12px] font-mono leading-5 text-[var(--color-ink)]">
                  {prettyJson((meta as Record<string, unknown>).before)}
                </pre>
              </div>
              <div>
                <h4 className="mb-2 text-[11px] font-bold uppercase tracking-wider text-emerald-700">
                  After
                </h4>
                <pre className="max-h-[480px] overflow-auto rounded-lg bg-emerald-50/40 p-3 text-[12px] font-mono leading-5 text-[var(--color-ink)]">
                  {prettyJson((meta as Record<string, unknown>).after)}
                </pre>
              </div>
            </div>
          ) : meta ? (
            <pre className="max-h-[480px] overflow-auto rounded-lg bg-[var(--color-mist)]/40 p-4 text-[12px] font-mono leading-5 text-[var(--color-ink)]">
              {prettyJson(meta)}
            </pre>
          ) : (
            <p className="text-[13px] text-[var(--color-slate)]">
              No metadata was attached to this event.
            </p>
          )}
        </FormSection>

        <FormSection title="Context">
          <dl className="grid gap-4 text-[13px]">
            <div>
              <dt className="flex items-center gap-1.5 text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
                <UserIcon className="h-3 w-3" aria-hidden />
                Admin
              </dt>
              <dd className="mt-1 text-[var(--color-ink)]">
                {row.adminName ?? "System"}
                {row.adminEmail && (
                  <span className="block text-[12px] text-[var(--color-slate)]">
                    {row.adminEmail}
                  </span>
                )}
              </dd>
            </div>
            <div>
              <dt className="flex items-center gap-1.5 text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
                <Link2 className="h-3 w-3" aria-hidden />
                Target
              </dt>
              <dd className="mt-1 font-mono text-[12px] text-[var(--color-slate)] break-all">
                {row.event.targetId ?? "—"}
              </dd>
            </div>
            <div>
              <dt className="flex items-center gap-1.5 text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
                <Clock className="h-3 w-3" aria-hidden />
                When
              </dt>
              <dd className="mt-1 text-[var(--color-ink)]">
                {formatAdminDateTime(row.event.createdAt)}
                <span className="block text-[12px] text-[var(--color-slate)]">
                  {formatAdminRelative(row.event.createdAt)}
                </span>
              </dd>
            </div>
            <div>
              <dt className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
                Event ID
              </dt>
              <dd className="mt-1 font-mono text-[12px] text-[var(--color-slate)] break-all">
                {row.event.id}
              </dd>
            </div>
          </dl>
        </FormSection>
      </div>
    </>
  );
}
