"use client";

import { useActionState } from "react";
import { createApiKey } from "@/lib/actions/admin";

export function NewApiKeyForm() {
  const [state, formAction, isPending] = useActionState(createApiKey, undefined);

  return (
    <div className="rounded-lg border border-charcoal/10 bg-warm-white p-4">
      <form action={formAction} className="flex items-end gap-2">
        <label className="flex flex-col gap-1">
          <span className="text-sm font-medium text-charcoal">Key name</span>
          <input
            type="text"
            name="name"
            placeholder="e.g. Pipe Tool production"
            required
            className="w-64 rounded border border-charcoal/20 bg-cream px-3 py-1.5 text-sm text-charcoal"
          />
        </label>
        <button
          type="submit"
          disabled={isPending}
          className="rounded-full bg-terracotta px-5 py-2 text-sm font-medium text-white hover:bg-terracotta/90 disabled:opacity-60"
        >
          {isPending ? "Generating..." : "Generate key"}
        </button>
      </form>
      {state?.error && <p className="mt-2 text-sm text-terracotta">{state.error}</p>}
      {state?.rawKey && (
        <div className="mt-3 rounded border border-gold/40 bg-gold/10 p-3">
          <p className="text-sm font-medium text-charcoal">
            Copy this key now. It won&apos;t be shown again.
          </p>
          <code className="mt-1 block break-all text-sm text-charcoal">
            {state.rawKey}
          </code>
        </div>
      )}
    </div>
  );
}
