"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useState } from "react";
import { cn } from "@stigmer/theme";
import { getUserMessage } from "@stigmer/sdk";
import { timestampDate } from "@bufbuild/protobuf/wkt";
import { useApiKeyList } from "./useApiKeyList";
import { useDeleteApiKey } from "./useDeleteApiKey";
/**
 * Displays a list of {@link ApiKey} resources for the authenticated
 * identity with inline delete confirmation.
 *
 * Each key is rendered as a row showing name, fingerprint, creation
 * date, expiry, and last-used time. A delete button triggers an
 * inline confirmation — the row transforms to show confirm/cancel
 * actions.
 *
 * API keys are identity-scoped: the server returns all keys belonging
 * to the authenticated user, regardless of organization.
 *
 * All visual properties flow through `--stgm-*` design tokens.
 *
 * @example
 * ```tsx
 * <ApiKeyListPanel />
 *
 * <ApiKeyListPanel
 *   onRefetchRef={(refetch) => { listRefetchRef.current = refetch; }}
 * />
 * ```
 */
export function ApiKeyListPanel({ onRefetchRef, className, }) {
    const { apiKeys, isLoading, error, refetch } = useApiKeyList();
    const [confirmingId, setConfirmingId] = useState(null);
    if (onRefetchRef) {
        onRefetchRef(refetch);
    }
    if (isLoading) {
        return (_jsx("div", { className: cn("space-y-2", className), "aria-busy": "true", "aria-label": "Loading API keys", children: Array.from({ length: 2 }, (_, i) => (_jsx("div", { className: "bg-muted-subtle h-14 animate-pulse rounded-lg" }, i))) }));
    }
    if (error) {
        return (_jsx("p", { className: cn("text-destructive text-xs", className), role: "alert", children: getUserMessage(error) }));
    }
    if (apiKeys.length === 0) {
        return (_jsx("p", { className: cn("text-muted-foreground py-4 text-center text-xs", className), children: "No API keys yet." }));
    }
    return (_jsx("div", { className: cn("space-y-2", className), role: "list", "aria-label": "API keys", children: apiKeys.map((key) => {
            const id = key.metadata?.id ?? "";
            return (_jsx(ApiKeyRow, { apiKey: key, isConfirming: confirmingId === id, onConfirmDelete: () => setConfirmingId(id), onCancelDelete: () => setConfirmingId(null), onDeleted: () => {
                    setConfirmingId(null);
                    refetch();
                } }, id));
        }) }));
}
// ---------------------------------------------------------------------------
// ApiKeyRow (internal)
// ---------------------------------------------------------------------------
function ApiKeyRow({ apiKey, isConfirming, onConfirmDelete, onCancelDelete, onDeleted, }) {
    const { deleteKey, isDeleting, error } = useDeleteApiKey();
    const id = apiKey.metadata?.id ?? "";
    const name = apiKey.metadata?.name || apiKey.metadata?.slug || "Unnamed key";
    const fingerprint = apiKey.spec?.fingerprint;
    const neverExpires = apiKey.spec?.neverExpires;
    const expiresAt = apiKey.spec?.expiresAt;
    const lastUsedAt = apiKey.status?.lastUsedAt;
    const createdAt = apiKey.status?.audit?.specAudit?.createdAt;
    const handleDelete = useCallback(async () => {
        try {
            await deleteKey(id);
            onDeleted();
        }
        catch {
            // error state is surfaced via the hook
        }
    }, [id, deleteKey, onDeleted]);
    if (isConfirming) {
        return (_jsxs("div", { role: "listitem", className: "flex items-center justify-between rounded-lg border border-destructive/30 bg-destructive-subtle px-3 py-2.5", children: [_jsxs("div", { className: "min-w-0 flex-1", children: [_jsxs("p", { className: "text-xs text-foreground", children: ["Delete ", _jsx("span", { className: "font-medium", children: name }), "?", fingerprint && (_jsxs("span", { className: "text-muted-foreground", children: [" ", "(\u2026", fingerprint, ")"] }))] }), error && (_jsx("p", { className: "mt-0.5 text-[0.65rem] text-destructive", children: getUserMessage(error) }))] }), _jsxs("div", { className: "flex shrink-0 items-center gap-1.5", children: [_jsxs("button", { type: "button", onClick: handleDelete, disabled: isDeleting, className: cn("inline-flex items-center gap-1 rounded-md px-2.5 py-1 text-xs font-medium", "bg-destructive text-destructive-foreground hover:bg-destructive-hover", "disabled:pointer-events-none disabled:opacity-50"), children: [isDeleting && _jsx(SpinnerIcon, {}), "Delete"] }), _jsx("button", { type: "button", onClick: onCancelDelete, disabled: isDeleting, className: cn("rounded-md px-2.5 py-1 text-xs", "text-muted-foreground hover:text-foreground hover:bg-accent-hover", "disabled:pointer-events-none disabled:opacity-50"), children: "Cancel" })] })] }));
    }
    return (_jsxs("div", { role: "listitem", className: "flex items-center gap-3 rounded-lg border border-border-muted px-3 py-2.5 hover:border-border transition-colors", children: [_jsx(KeyIcon, {}), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("span", { className: "block truncate text-sm font-medium text-foreground", children: name }), fingerprint && (_jsxs("span", { className: "block text-xs text-muted-foreground font-mono", children: ["\u2026", fingerprint] }))] }), _jsxs("div", { className: "hidden sm:flex shrink-0 items-center gap-4 text-xs text-muted-foreground", children: [createdAt && (_jsx("span", { title: `Created ${timestampDate(createdAt).toISOString()}`, children: formatShortDate(timestampDate(createdAt)) })), _jsx("span", { children: neverExpires
                            ? "No expiry"
                            : expiresAt
                                ? `Expires ${formatShortDate(timestampDate(expiresAt))}`
                                : "No expiry" }), _jsx("span", { children: lastUsedAt ? formatRelativeTime(timestampDate(lastUsedAt)) : "Never used" })] }), _jsx("button", { type: "button", onClick: onConfirmDelete, "aria-label": `Delete ${name}`, className: cn("shrink-0 rounded p-1", "text-muted-foreground hover:text-destructive hover:bg-destructive-subtle", "transition-colors"), children: _jsx(TrashIcon, {}) })] }));
}
// ---------------------------------------------------------------------------
// Formatting helpers
// ---------------------------------------------------------------------------
function formatShortDate(date) {
    return date.toLocaleDateString(undefined, {
        month: "short",
        day: "numeric",
        year: "numeric",
    });
}
function formatRelativeTime(date) {
    const now = Date.now();
    const diffMs = now - date.getTime();
    if (diffMs < 0)
        return "Just now";
    const seconds = Math.floor(diffMs / 1000);
    if (seconds < 60)
        return "Just now";
    const minutes = Math.floor(seconds / 60);
    if (minutes < 60)
        return `${minutes}m ago`;
    const hours = Math.floor(minutes / 60);
    if (hours < 24)
        return `${hours}h ago`;
    const days = Math.floor(hours / 24);
    if (days < 30)
        return `${days}d ago`;
    return formatShortDate(date);
}
// ---------------------------------------------------------------------------
// Icons
// ---------------------------------------------------------------------------
function KeyIcon() {
    return (_jsxs("svg", { width: "14", height: "14", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", className: "shrink-0 text-muted-foreground", children: [_jsx("circle", { cx: "5.5", cy: "10.5", r: "3" }), _jsx("path", { d: "M8 8l5.5-5.5M11 5l2-2M10.5 2.5l2 2" })] }));
}
function TrashIcon() {
    return (_jsxs("svg", { width: "14", height: "14", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: [_jsx("path", { d: "M2.5 4h11M5.5 4V2.5a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1V4" }), _jsx("path", { d: "M12.5 4v9a1 1 0 0 1-1 1h-7a1 1 0 0 1-1-1V4" }), _jsx("line", { x1: "6.5", y1: "7", x2: "6.5", y2: "11" }), _jsx("line", { x1: "9.5", y1: "7", x2: "9.5", y2: "11" })] }));
}
function SpinnerIcon() {
    return (_jsx("svg", { width: "12", height: "12", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", className: "animate-spin", "aria-hidden": "true", children: _jsx("path", { d: "M8 2a6 6 0 1 0 6 6" }) }));
}
//# sourceMappingURL=ApiKeyListPanel.js.map