import prisma from "@/lib/prisma";
import { auth } from "@/lib/auth";
import { redirect } from "next/navigation";
import Link from "next/link";

export default async function AdminAuditLogPage({
  searchParams,
}: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  const session = await auth();
  if (!session?.user || session.user.userType !== "admin") {
    redirect("/login");
  }

  const params = await searchParams;
  const page = Math.max(1, parseInt(String(params.page ?? "1")));
  const perPage = 50;

  const [logs, total] = await Promise.all([
    prisma.auditLog.findMany({
      orderBy: { created_at: "desc" },
      skip: (page - 1) * perPage,
      take: perPage,
    }),
    prisma.auditLog.count(),
  ]);

  const totalPages = Math.ceil(total / perPage);

  function buildUrl(overrides: Record<string, string>) {
    const p = new URLSearchParams();
    p.set("page", String(page));
    Object.entries(overrides).forEach(([k, v]) => p.set(k, v));
    return `/admin/audit-log?${p.toString()}`;
  }

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-bold">Audit Log</h1>

      <p className="text-text-muted text-sm">
        Showing {(page - 1) * perPage + 1}-
        {Math.min(page * perPage, total)} of {total.toLocaleString()} entries
      </p>

      <div className="bg-surface rounded-lg overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead>
              <tr className="border-b border-surface-light text-text-muted text-sm">
                <th className="p-4 font-medium">ID</th>
                <th className="p-4 font-medium">Admin ID</th>
                <th className="p-4 font-medium">Action</th>
                <th className="p-4 font-medium">Target</th>
                <th className="p-4 font-medium">Details</th>
                <th className="p-4 font-medium">IP</th>
                <th className="p-4 font-medium">Timestamp</th>
              </tr>
            </thead>
            <tbody>
              {logs.map((log) => (
                <tr
                  key={log.id}
                  className="border-b border-surface-light last:border-0 hover:bg-surface-light/50"
                >
                  <td className="p-4 text-text-muted font-mono text-sm">
                    {log.id}
                  </td>
                  <td className="p-4 text-text-muted">{log.admin_id}</td>
                  <td className="p-4">
                    <span className="inline-block px-2 py-0.5 rounded text-xs font-medium bg-surface-light">
                      {log.action}
                    </span>
                  </td>
                  <td className="p-4 text-text-muted text-sm">
                    {log.target_type} #{log.target_id}
                  </td>
                  <td className="p-4 text-text-muted text-sm max-w-[300px] truncate">
                    {log.details || "-"}
                  </td>
                  <td className="p-4 text-text-muted font-mono text-sm">
                    {log.ip_address || "-"}
                  </td>
                  <td className="p-4 text-text-muted text-sm whitespace-nowrap">
                    {new Date(log.created_at).toLocaleString()}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex items-center justify-center gap-2">
          {page > 1 && (
            <Link
              href={buildUrl({ page: String(page - 1) })}
              className="bg-surface hover:bg-surface-light text-text-muted px-3 py-1.5 rounded transition-colors text-sm"
            >
              Previous
            </Link>
          )}
          {Array.from({ length: Math.min(totalPages, 7) }, (_, i) => {
            let pageNum: number;
            if (totalPages <= 7) {
              pageNum = i + 1;
            } else if (page <= 4) {
              pageNum = i + 1;
            } else if (page >= totalPages - 3) {
              pageNum = totalPages - 6 + i;
            } else {
              pageNum = page - 3 + i;
            }
            return (
              <Link
                key={pageNum}
                href={buildUrl({ page: String(pageNum) })}
                className={`px-3 py-1.5 rounded text-sm transition-colors ${
                  pageNum === page
                    ? "bg-primary text-white"
                    : "bg-surface hover:bg-surface-light text-text-muted"
                }`}
              >
                {pageNum}
              </Link>
            );
          })}
          {page < totalPages && (
            <Link
              href={buildUrl({ page: String(page + 1) })}
              className="bg-surface hover:bg-surface-light text-text-muted px-3 py-1.5 rounded transition-colors text-sm"
            >
              Next
            </Link>
          )}
        </div>
      )}
    </div>
  );
}
