import Link from "next/link";
import type { Metadata } from "next";
import { ArrowLeft, ScrollText } from "lucide-react";
import { UserRole } from "@prisma/client";

import { requireRole } from "@/lib/auth-utils";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { getAuditLogRows } from "../_lib/data";

export const metadata: Metadata = {
  title: "AuditLog · Kita-Planer",
};

function formatDate(date: Date) {
  return new Intl.DateTimeFormat("de-DE", {
    dateStyle: "medium",
    timeStyle: "short",
  }).format(date);
}

function actionLabel(action: string) {
  switch (action) {
    case "KITA_DIAGNOSTIC_VIEW":
      return "Diagnose geöffnet";
    case "KITA_DELETE":
      return "Kita gelöscht";
    case "USER_DELETE":
      return "Benutzer gelöscht";
    case "USER_LOCK":
      return "Benutzer gesperrt";
    case "USER_UNLOCK":
      return "Benutzer entsperrt";
    case "USER_FAILED_LOGIN_RESET":
      return "Fehlversuche zurückgesetzt";
    default:
      return action;
  }
}

function metadataPreview(metadata: unknown) {
  if (!metadata) return "—";
  const preview = JSON.stringify(metadata);
  if (!preview) return "—";
  return preview.length > 140 ? `${preview.slice(0, 140)}...` : preview;
}

export default async function AuditPage() {
  await requireRole([UserRole.SUPERADMIN]);
  const rows = await getAuditLogRows();

  return (
    <div className="px-8 py-8">
      <div className="mb-7 flex flex-wrap items-start justify-between gap-4">
        <div>
          <Button asChild variant="ghost" className="-ml-3 mb-3">
            <Link href="/admin">
              <ArrowLeft className="h-4 w-4" />
              Zur Kita-Übersicht
            </Link>
          </Button>
          <h1 className="text-2xl font-semibold tracking-tight">AuditLog</h1>
          <p className="mt-1 text-sm text-muted-foreground">
            Die letzten 200 Superadmin-Diagnose- und Support-Aktionen.
          </p>
        </div>
        <div className="flex h-10 w-10 items-center justify-center rounded-md bg-primary text-primary-foreground">
          <ScrollText className="h-5 w-5" />
        </div>
      </div>

      <Card>
        <CardHeader>
          <CardTitle as="h2" className="text-xl">
            Systemweite Aktionen
          </CardTitle>
          <CardDescription>
            Audit-Einträge sind unabhängig von gelöschten Kitas und Benutzern.
          </CardDescription>
        </CardHeader>
        <CardContent>
          {rows.length === 0 ? (
            <div className="rounded-md border border-dashed p-8 text-center text-sm text-muted-foreground">
              Noch keine Audit-Einträge vorhanden.
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Zeitpunkt</TableHead>
                  <TableHead>Aktion</TableHead>
                  <TableHead>Akteur</TableHead>
                  <TableHead>Ziel</TableHead>
                  <TableHead>Metadaten</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {rows.map((row) => (
                  <TableRow key={row.id}>
                    <TableCell className="whitespace-nowrap">
                      {formatDate(row.createdAt)}
                    </TableCell>
                    <TableCell>
                      <Badge
                        variant={
                          row.action.endsWith("_DELETE")
                            ? "destructive"
                            : "secondary"
                        }
                      >
                        {actionLabel(row.action)}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm">{row.actorEmail}</span>
                    </TableCell>
                    <TableCell>
                      <div className="font-medium">{row.targetLabel}</div>
                      <div className="text-xs text-muted-foreground">
                        {row.targetType} · {row.targetId}
                      </div>
                    </TableCell>
                    <TableCell className="max-w-sm">
                      <code className="block truncate rounded bg-muted px-2 py-1 text-xs">
                        {metadataPreview(row.metadata)}
                      </code>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>
    </div>
  );
}

