"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useState } from "react";
import { cn } from "@stigmer/theme";
import { timestampDate } from "@bufbuild/protobuf/wkt";
import { ApiResourceVisibility } from "@stigmer/protos/ai/stigmer/commons/apiresource/enum_pb";
import { ApiResourceKind } from "@stigmer/protos/ai/stigmer/commons/apiresource/apiresourcekind/api_resource_kind_pb";
import { getUserMessage } from "@stigmer/sdk";
import { useUpdateWorkflowInstance } from "./useUpdateWorkflowInstance";
import { useDeleteWorkflowInstance } from "./useDeleteWorkflowInstance";
import { useUpdateVisibility } from "../../library/useUpdateVisibility";
import { InstanceVisibilitySelector } from "../../library/InstanceVisibilitySelector";
import { PermissionGate } from "../../iam-policy/PermissionGate";
import { SharePanel } from "../../iam-policy/SharePanel";
import { EnvironmentPicker } from "../../environment/EnvironmentPicker";
import { useEnvironmentList } from "../../environment/useEnvironmentList";
/**
 * Expandable detail panel for a single WorkflowInstance.
 *
 * Shows metadata, description (inline-editable), environment bindings (editable),
 * visibility control, share panel (FGA-gated), and a delete action with cascade warning.
 */
export function WorkflowInstanceDetailPanel({ instance, org, onClose, onDeleted, onRunClick, onUpdated, }) {
    const meta = instance.metadata;
    const id = meta?.id ?? "";
    const spec = instance.spec;
    const { update, isUpdating } = useUpdateWorkflowInstance();
    const { deleteInstance, isDeleting } = useDeleteWorkflowInstance();
    const { updateVisibility, isPending: isVisibilityPending } = useUpdateVisibility("workflowInstance", id || null);
    const { environments } = useEnvironmentList(org);
    const [isEditingEnvs, setIsEditingEnvs] = useState(false);
    const [editEnvRefs, setEditEnvRefs] = useState([]);
    const [showSharePanel, setShowSharePanel] = useState(false);
    const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
    const [deleteError, setDeleteError] = useState(null);
    const handleVisibilityChange = useCallback(async (v) => {
        await updateVisibility(v);
        onUpdated?.();
    }, [updateVisibility, onUpdated]);
    const handleStartEditEnvs = useCallback(() => {
        const currentRefs = (spec?.environmentRefs ?? []).map((ref) => ({
            org: ref.org || org,
            slug: ref.slug,
        }));
        setEditEnvRefs(currentRefs);
        setIsEditingEnvs(true);
    }, [spec?.environmentRefs, org]);
    const handleSaveEnvs = useCallback(async () => {
        try {
            await update({
                name: meta?.name ?? "",
                org: meta?.org ?? org,
                workflowId: spec?.workflowId ?? "",
                description: spec?.description,
                environmentRefs: editEnvRefs,
                visibility: meta?.visibility,
            });
            setIsEditingEnvs(false);
            onUpdated?.();
        }
        catch {
            // error displayed by hook
        }
    }, [update, meta, spec, org, editEnvRefs, onUpdated]);
    const handleDelete = useCallback(async () => {
        setDeleteError(null);
        try {
            await deleteInstance(id);
            onDeleted?.();
        }
        catch (err) {
            setDeleteError(err instanceof Error ? err : new Error("Failed to delete instance"));
        }
    }, [deleteInstance, id, onDeleted]);
    const resolveEnvName = useCallback((slug) => {
        const env = environments.find((e) => e.metadata?.slug === slug);
        return env?.metadata?.name ?? slug;
    }, [environments]);
    const audit = instance.status?.audit?.specAudit;
    const createdAt = audit?.createdAt ? timestampDate(audit.createdAt) : null;
    const updatedAt = audit?.updatedAt ? timestampDate(audit.updatedAt) : null;
    return (_jsxs("div", { className: "border border-border rounded-lg bg-background overflow-hidden", children: [_jsxs("div", { className: "flex items-center justify-between border-b border-border px-4 py-3", children: [_jsxs("div", { children: [_jsx("h3", { className: "text-sm font-semibold text-foreground", children: meta?.name || meta?.slug || "Instance" }), _jsxs("p", { className: "text-[0.65rem] text-muted-foreground", children: [createdAt && `Created ${createdAt.toLocaleDateString()}`, updatedAt && ` · Updated ${updatedAt.toLocaleDateString()}`] })] }), _jsxs("div", { className: "flex items-center gap-2", children: [onRunClick && (_jsx("button", { type: "button", onClick: () => onRunClick(instance), className: cn("rounded-md px-2.5 py-1 text-xs font-medium", "bg-primary text-primary-foreground hover:bg-primary/90", "focus:outline-none focus:ring-2 focus:ring-ring"), children: "Run" })), _jsx(PermissionGate, { resource: { kind: "workflow_instance", id }, relation: "can_grant_access", children: _jsx("button", { type: "button", onClick: () => setShowSharePanel((v) => !v), className: cn("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: "Share" }) }), _jsx("button", { type: "button", onClick: onClose, "aria-label": "Close panel", className: cn("rounded-md p-1 text-muted-foreground", "hover:text-foreground hover:bg-accent-hover"), children: _jsx(CloseIcon, {}) })] })] }), _jsxs("div", { className: "divide-y divide-border", children: [spec?.description && (_jsxs("div", { className: "px-4 py-3", children: [_jsx("h4", { className: "text-xs font-medium text-muted-foreground mb-1", children: "Description" }), _jsx("p", { className: "text-sm text-foreground", children: spec.description })] })), _jsxs("div", { className: "px-4 py-3", children: [_jsxs("div", { className: "flex items-center justify-between mb-2", children: [_jsxs("h4", { className: "text-xs font-medium text-muted-foreground", children: ["Environments (", spec?.environmentRefs?.length ?? 0, ")"] }), !isEditingEnvs && (_jsx(PermissionGate, { resource: { kind: "workflow_instance", id }, relation: "can_edit", children: _jsx("button", { type: "button", onClick: handleStartEditEnvs, className: "text-[0.65rem] text-primary hover:underline", children: "Edit" }) }))] }), isEditingEnvs ? (_jsxs("div", { className: "space-y-2", children: [_jsx(EnvironmentPicker, { org: org, value: editEnvRefs, onChange: setEditEnvRefs, disabled: isUpdating }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx("button", { type: "button", onClick: handleSaveEnvs, disabled: isUpdating, className: cn("rounded-md px-2.5 py-1 text-xs font-medium", "bg-primary text-primary-foreground hover:bg-primary/90", "disabled:opacity-50"), children: isUpdating ? "Saving..." : "Save" }), _jsx("button", { type: "button", onClick: () => setIsEditingEnvs(false), disabled: isUpdating, className: "rounded-md px-2.5 py-1 text-xs font-medium text-foreground hover:bg-accent-hover", children: "Cancel" })] })] })) : (_jsx("div", { children: (spec?.environmentRefs?.length ?? 0) === 0 ? (_jsx("p", { className: "text-xs text-muted-foreground", children: "No environments bound." })) : (_jsx("ol", { className: "space-y-1", children: spec.environmentRefs.map((ref, idx) => (_jsxs("li", { className: "flex items-center gap-2 text-sm", children: [_jsxs("span", { className: "text-xs text-muted-foreground w-4 text-right", children: [idx + 1, "."] }), _jsx("span", { className: "text-foreground", children: resolveEnvName(ref.slug) })] }, `${ref.slug}-${idx}`))) })) }))] }), _jsxs("div", { className: "px-4 py-3", children: [_jsx("h4", { className: "text-xs font-medium text-muted-foreground mb-2", children: "Visibility" }), _jsx(PermissionGate, { resource: { kind: "workflow_instance", id }, relation: "can_edit", fallback: _jsx("span", { className: "text-sm text-foreground", children: VISIBILITY_LABELS[meta?.visibility ?? 0] ?? "Private" }), children: _jsx(InstanceVisibilitySelector, { visibility: meta?.visibility ?? ApiResourceVisibility.visibility_private, onVisibilityChange: handleVisibilityChange, isPending: isVisibilityPending }) })] }), showSharePanel && (_jsx("div", { className: "px-4 py-3", children: _jsx(SharePanel, { resource: { kind: "workflow_instance", id, resourceKind: ApiResourceKind.workflow_instance }, resourceKindString: "workflow_instance", resourceKind: ApiResourceKind.workflow_instance, onClose: () => setShowSharePanel(false) }) })), _jsx(PermissionGate, { resource: { kind: "workflow_instance", id }, relation: "can_delete", children: _jsxs("div", { className: "px-4 py-3", children: [_jsx("h4", { className: "text-xs font-medium text-destructive mb-2", children: "Danger Zone" }), !showDeleteConfirm ? (_jsx("button", { type: "button", onClick: () => setShowDeleteConfirm(true), className: cn("rounded-md px-3 py-1.5 text-xs font-medium", "border border-destructive/30 text-destructive", "hover:bg-destructive/10", "focus:outline-none focus:ring-2 focus:ring-destructive"), children: "Delete Instance" })) : (_jsxs("div", { className: "space-y-2 rounded-md border border-destructive/30 p-3 bg-destructive/5", children: [_jsx("p", { className: "text-xs text-destructive font-medium", children: "This will permanently delete this instance and all its execution history. This action cannot be undone." }), deleteError && (_jsx("p", { className: "text-xs text-destructive", role: "alert", children: getUserMessage(deleteError) })), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx("button", { type: "button", onClick: handleDelete, disabled: isDeleting, className: cn("rounded-md px-3 py-1.5 text-xs font-medium", "bg-destructive text-destructive-foreground", "hover:bg-destructive/90", "disabled:opacity-50"), children: isDeleting ? "Deleting..." : "Confirm Delete" }), _jsx("button", { type: "button", onClick: () => setShowDeleteConfirm(false), disabled: isDeleting, className: "rounded-md px-3 py-1.5 text-xs font-medium text-foreground hover:bg-accent-hover", children: "Cancel" })] })] }))] }) })] })] }));
}
const VISIBILITY_LABELS = {
    [ApiResourceVisibility.visibility_private]: "Private",
    [ApiResourceVisibility.visibility_org]: "Organization",
    [ApiResourceVisibility.visibility_public]: "Public",
};
function CloseIcon() {
    return (_jsx("svg", { width: "14", height: "14", viewBox: "0 0 14 14", fill: "none", "aria-hidden": "true", children: _jsx("path", { d: "M3 3l8 8M11 3l-8 8", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round" }) }));
}
//# sourceMappingURL=WorkflowInstanceDetailPanel.js.map