import { db } from "@/lib/db";
import { NewApiKeyForm } from "./NewApiKeyForm";
import { RevokeApiKeyButton } from "./RevokeApiKeyButton";
import { AdminOnlyGate } from "../AdminOnlyGate";

export default async function AdminApiKeysPage() {
  const keys = await db.apiKey.findMany({
    orderBy: { createdAt: "desc" },
    include: { createdBy: true },
  });

  return (
    <AdminOnlyGate>
    <div>
      <h1 className="font-heading text-3xl font-semibold text-terracotta">
        API Keys
      </h1>
      <p className="mt-2 text-charcoal/60">
        Keys for Pipe Tool integration. The full key is shown only once when
        created.
      </p>

      <div className="mt-6">
        <NewApiKeyForm />
      </div>

      {keys.length === 0 ? (
        <p className="mt-8 text-charcoal/60">No API keys yet.</p>
      ) : (
        <ul className="mt-8 flex flex-col gap-3">
          {keys.map((key) => (
            <li
              key={key.id}
              className="flex items-center justify-between gap-4 rounded-lg border border-charcoal/10 bg-warm-white p-4"
            >
              <div>
                <p className="font-medium text-charcoal">
                  {key.name}
                  {key.revokedAt && (
                    <span className="ml-2 rounded-full bg-charcoal/10 px-2 py-0.5 text-xs font-medium text-charcoal/60">
                      Revoked
                    </span>
                  )}
                </p>
                <p className="text-sm text-charcoal/60">
                  {key.keyPrefix}&hellip; &middot; created by{" "}
                  {key.createdBy.username} on {key.createdAt.toLocaleDateString()}
                  {key.lastUsedAt
                    ? ` · last used ${key.lastUsedAt.toLocaleDateString()}`
                    : " · never used"}
                </p>
              </div>
              {!key.revokedAt && <RevokeApiKeyButton keyId={key.id} />}
            </li>
          ))}
        </ul>
      )}
    </div>
    </AdminOnlyGate>
  );
}
