"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 { usePlatformClientList } from "./usePlatformClientList";
import { useDeletePlatformClient } from "./useDeletePlatformClient";
/**
 * Displays a list of {@link PlatformClient} resources for an
 * organization with inline delete confirmation.
 *
 * Each row shows the client name, `client_id` (monospace), secret
 * fingerprint, expiry status, and creation date. A delete button
 * triggers an inline confirmation flow.
 *
 * Platform clients are admin-level resources with small cardinality
 * (typically 1–5 per org), so the list is rendered without pagination.
 *
 * All visual properties flow through `--stgm-*` design tokens.
 *
 * @example
 * ```tsx
 * <PlatformClientListPanel org="acme" />
 * ```
 *
 * @example
 * ```tsx
 * <PlatformClientListPanel
 *   org="acme"
 *   onEdit={(pc) => setFlow({ phase: "editing", platformClient: pc })}
 *   onRefetchRef={(refetch) => { listRefetchRef.current = refetch; }}
 * />
 * ```
 */
export function PlatformClientListPanel({ org, onEdit, onRefetchRef, className, }) {
    const { platformClients, isLoading, error, refetch } = usePlatformClientList(org);
    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 platform clients", 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 (platformClients.length === 0) {
        return (_jsx("p", { className: cn("text-muted-foreground py-4 text-center text-xs", className), children: "No platform clients configured." }));
    }
    return (_jsx("div", { className: cn("space-y-2", className), role: "list", "aria-label": "Platform clients", children: platformClients.map((pc) => {
            const id = pc.metadata?.id ?? "";
            return (_jsx(PlatformClientRow, { platformClient: pc, isConfirming: confirmingId === id, onEdit: onEdit ? () => onEdit(pc) : undefined, onConfirmDelete: () => setConfirmingId(id), onCancelDelete: () => setConfirmingId(null), onDeleted: () => {
                    setConfirmingId(null);
                    refetch();
                } }, id));
        }) }));
}
// ---------------------------------------------------------------------------
// PlatformClientRow (internal)
// ---------------------------------------------------------------------------
function PlatformClientRow({ platformClient, isConfirming, onEdit, onConfirmDelete, onCancelDelete, onDeleted, }) {
    const { deletePlatformClient, isDeleting, error } = useDeletePlatformClient();
    const id = platformClient.metadata?.id ?? "";
    const spec = platformClient.spec;
    const name = platformClient.metadata?.name ?? "Unnamed client";
    const clientId = spec?.clientId ?? "";
    const fingerprint = spec?.secretFingerprint ?? "";
    const createdAt = platformClient.status?.audit?.specAudit?.createdAt;
    const handleDelete = useCallback(async () => {
        try {
            await deletePlatformClient({ resourceId: id });
            onDeleted();
        }
        catch {
            // error state is surfaced via the hook
        }
    }, [id, deletePlatformClient, 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 }), "?", clientId && (_jsxs("span", { className: "ml-1 text-muted-foreground", children: ["This will invalidate client ID", " ", _jsx("code", { className: "font-mono", children: clientId }), "."] }))] }), 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 }), clientId && (_jsx("span", { className: "block truncate text-xs text-muted-foreground font-mono", children: clientId }))] }), _jsxs("div", { className: "hidden sm:flex shrink-0 items-center gap-3 text-xs text-muted-foreground", children: [fingerprint && (_jsxs("span", { className: "font-mono", title: `Secret fingerprint: ${fingerprint}`, children: ["\u2022\u2022\u2022\u2022", fingerprint.slice(-4)] })), _jsx(ExpiryBadge, { spec: spec }), spec?.autoProvisionAccounts && (_jsx("span", { className: "inline-flex items-center rounded-full border border-primary/30 bg-primary-subtle px-2 py-0.5 text-[0.65rem] font-medium text-primary", children: "JIT" })), createdAt && (_jsx("span", { title: `Created ${timestampDate(createdAt).toISOString()}`, children: formatShortDate(timestampDate(createdAt)) }))] }), _jsxs("div", { className: "flex shrink-0 items-center gap-1", children: [onEdit && (_jsx("button", { type: "button", onClick: onEdit, "aria-label": `Edit ${name}`, className: cn("shrink-0 rounded p-1", "text-muted-foreground hover:text-foreground hover:bg-accent-hover", "transition-colors"), children: _jsx(PencilIcon, {}) })), _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, {}) })] })] }));
}
// ---------------------------------------------------------------------------
// ExpiryBadge (internal)
// ---------------------------------------------------------------------------
function ExpiryBadge({ spec }) {
    if (spec?.neverExpires) {
        return (_jsx("span", { className: "text-[0.65rem] text-muted-foreground", children: "No expiry" }));
    }
    if (spec?.expiresAt) {
        const date = timestampDate(spec.expiresAt);
        const isExpired = date < new Date();
        return (_jsx("span", { className: cn("text-[0.65rem]", isExpired ? "text-destructive font-medium" : "text-muted-foreground"), title: `Expires ${date.toISOString()}`, children: isExpired ? "Expired" : `Exp ${formatShortDate(date)}` }));
    }
    return null;
}
// ---------------------------------------------------------------------------
// Formatting helpers
// ---------------------------------------------------------------------------
function formatShortDate(date) {
    return date.toLocaleDateString(undefined, {
        month: "short",
        day: "numeric",
        year: "numeric",
    });
}
// ---------------------------------------------------------------------------
// 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: "10.5", cy: "5.5", r: "3" }), _jsx("path", { d: "M8.5 7.5L3 13l-.5-2.5L5 10l1-1-1-1 3.5.5z" })] }));
}
function PencilIcon() {
    return (_jsx("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: "M11 2.5l2.5 2.5L5 13.5H2.5V11L11 2.5z" }) }));
}
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=PlatformClientListPanel.js.map