"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useRef } from "react";
import { cn } from "@stigmer/theme";
import { ApiResourceVisibility } from "@stigmer/protos/ai/stigmer/commons/apiresource/enum_pb";
import { useWorkflowInstances } from "../useWorkflowInstances.js";
import { useEnvironmentList } from "../../environment/useEnvironmentList.js";
import { ResourceVisibilityControl } from "../../library/ResourceVisibilityControl.js";
import { PermissionGate } from "../../iam-policy/PermissionGate.js";
import { WorkflowInstanceEmptyState } from "./WorkflowInstanceEmptyState.js";
/**
 * Enhanced workflow instance list with environment badges, visibility controls,
 * and action buttons. Filters out the platform-managed default instance.
 *
 * This is an SDK component (DD-001) — embeddable by platform builders.
 */
export function WorkflowInstanceList({ workflowId, defaultInstanceId, org, onCreateClick, onInstanceClick, onRunClick, onDeleteClick, refreshKey, className, }) {
    const { instances, isLoading, error, refetch } = useWorkflowInstances(workflowId);
    const { environments } = useEnvironmentList(org);
    // Refetch when refreshKey changes (signals external mutation like create/delete)
    const prevRefreshKey = useRef(refreshKey);
    useEffect(() => {
        if (refreshKey !== undefined && refreshKey !== prevRefreshKey.current) {
            prevRefreshKey.current = refreshKey;
            refetch();
        }
    }, [refreshKey, refetch]);
    const userInstances = useMemo(() => instances.filter((i) => i.metadata?.id !== defaultInstanceId), [instances, defaultInstanceId]);
    const resolveEnvName = useCallback((slug) => {
        const env = environments.find((e) => e.metadata?.slug === slug);
        return env?.metadata?.name ?? slug;
    }, [environments]);
    if (isLoading) {
        return _jsx(LoadingSkeleton, {});
    }
    if (error) {
        return (_jsx("div", { className: "py-8 text-center text-sm text-destructive", children: "Failed to load instances" }));
    }
    if (userInstances.length === 0) {
        return _jsx(WorkflowInstanceEmptyState, { onCreateClick: onCreateClick, className: className });
    }
    return (_jsxs("div", { className: cn("space-y-3", className), children: [_jsxs("div", { className: "flex items-center justify-between", children: [_jsxs("h3", { className: "text-sm font-medium text-foreground", children: [userInstances.length, " ", userInstances.length === 1 ? "instance" : "instances"] }), onCreateClick && (_jsxs("button", { type: "button", onClick: onCreateClick, className: cn("inline-flex items-center gap-1 rounded-md px-2.5 py-1", "text-xs font-medium", "border border-border text-foreground", "hover:bg-accent-hover", "focus:outline-none focus:ring-2 focus:ring-ring"), children: [_jsx(PlusIcon, {}), "Create"] }))] }), _jsx("div", { className: "overflow-hidden rounded-lg border border-border", children: _jsxs("table", { className: "w-full text-sm", children: [_jsx("thead", { children: _jsxs("tr", { className: "border-b border-border bg-muted/50", children: [_jsx("th", { className: "px-4 py-2 text-left font-medium text-muted-foreground", children: "Name" }), _jsx("th", { className: "px-4 py-2 text-left font-medium text-muted-foreground", children: "Environments" }), _jsx("th", { className: "px-4 py-2 text-left font-medium text-muted-foreground", children: "Visibility" }), _jsx("th", { className: "px-4 py-2 text-right font-medium text-muted-foreground", children: "Actions" })] }) }), _jsx("tbody", { className: "divide-y divide-border", children: userInstances.map((inst) => (_jsx(InstanceRow, { instance: inst, resolveEnvName: resolveEnvName, onRowClick: onInstanceClick, onRunClick: onRunClick, onDeleteClick: onDeleteClick, refetch: refetch }, inst.metadata?.id))) })] }) })] }));
}
function InstanceRow({ instance, resolveEnvName, onRowClick, onRunClick, onDeleteClick, refetch, }) {
    const meta = instance.metadata;
    const id = meta?.id ?? "";
    const envRefs = instance.spec?.environmentRefs ?? [];
    return (_jsxs("tr", { className: cn("transition-colors", onRowClick && "cursor-pointer hover:bg-muted/30"), onClick: () => onRowClick?.(instance), children: [_jsx("td", { className: "px-4 py-2.5", children: _jsxs("div", { children: [_jsx("span", { className: "font-medium text-foreground", children: meta?.name || meta?.slug || "—" }), instance.spec?.description && (_jsx("p", { className: "text-[0.65rem] text-muted-foreground truncate max-w-48", children: instance.spec.description }))] }) }), _jsx("td", { className: "px-4 py-2.5", children: envRefs.length === 0 ? (_jsx("span", { className: "text-xs text-muted-foreground", children: "None" })) : (_jsx("div", { className: "flex flex-wrap gap-1", children: envRefs.map((ref, idx) => (_jsx("span", { className: cn("inline-flex items-center rounded-md px-1.5 py-0.5", "text-[0.65rem] font-medium", "bg-muted text-muted-foreground", "border border-border"), children: resolveEnvName(ref.slug) }, `${ref.slug}-${idx}`))) })) }), _jsx("td", { className: "px-4 py-2.5", onClick: (e) => e.stopPropagation(), children: id ? (_jsx(ResourceVisibilityControl, { kind: "workflowInstance", resourceId: id, visibility: meta?.visibility ?? ApiResourceVisibility.visibility_private, onChanged: refetch })) : (_jsx("span", { className: "text-xs text-muted-foreground", children: "\u2014" })) }), _jsx("td", { className: "px-4 py-2.5 text-right", onClick: (e) => e.stopPropagation(), children: _jsxs("div", { className: "flex items-center justify-end gap-1", children: [onRunClick && (_jsx("button", { type: "button", onClick: () => onRunClick(instance), className: cn("rounded px-2 py-1 text-xs font-medium", "text-foreground hover:bg-accent-hover", "focus:outline-none focus:ring-1 focus:ring-ring"), children: "Run" })), onDeleteClick && (_jsx(PermissionGate, { resource: { kind: "workflow_instance", id }, relation: "can_delete", children: _jsx("button", { type: "button", onClick: () => onDeleteClick(instance), className: cn("rounded px-2 py-1 text-xs font-medium", "text-destructive hover:bg-destructive/10", "focus:outline-none focus:ring-1 focus:ring-ring"), children: "Delete" }) }))] }) })] }));
}
function LoadingSkeleton() {
    return (_jsx("div", { className: "space-y-2 py-4", children: [1, 2, 3].map((i) => (_jsx("div", { className: "h-12 rounded-md bg-muted/50 animate-pulse" }, i))) }));
}
function PlusIcon() {
    return (_jsx("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", "aria-hidden": "true", children: _jsx("path", { d: "M6 2v8M2 6h8", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round" }) }));
}
//# sourceMappingURL=WorkflowInstanceList.js.map