"use client";
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { cn } from "@stigmer/theme";
import { timestampDate } from "@bufbuild/protobuf/wkt";
import { ValidationState } from "@stigmer/protos/ai/stigmer/agentic/workflow/v1/serverless/validation_pb";
import { useWorkflow } from "./useWorkflow.js";
import { useUpdateWorkflow } from "./useUpdateWorkflow.js";
import { workflowToInput } from "./internal/workflowToInput.js";
import { useWorkflowExecutionList } from "./useWorkflowExecutionList.js";
import { useWorkflowDashboardSummary } from "./useWorkflowDashboardSummary.js";
import { WorkflowOverviewGraph } from "./WorkflowOverviewGraph.js";
import { WorkflowGraphFullscreenDialog } from "./WorkflowGraphFullscreenDialog.js";
import { WorkflowOverviewSummary } from "./WorkflowOverviewSummary.js";
import { WorkflowExplainDialog } from "./WorkflowExplainDialog.js";
import { serializeWorkflowYaml } from "./serialize-workflow-yaml.js";
import { WorkflowExecutionHistory } from "./execution-history/WorkflowExecutionHistory.js";
import { WorkflowInstanceList } from "./instance/WorkflowInstanceList.js";
import { WorkflowVersionsTab } from "./WorkflowVersionsTab.js";
import { useWorkflowVersions } from "./useWorkflowVersions.js";
import { ErrorMessage } from "../error/ErrorMessage.js";
import { VisibilityBadge } from "../library/VisibilitySelector.js";
import { useManageAccess } from "../access/useManageAccess.js";
import { ApiResourceKind } from "@stigmer/protos/ai/stigmer/commons/apiresource/apiresourcekind/api_resource_kind_pb";
import { formatDurationSec } from "./format-utils.js";
import { ResourceDetailShell } from "../resource-detail/ResourceDetailShell.js";
import { Section } from "../resource-detail/Section.js";
import { useDetailTabs } from "../resource-detail/useDetailTabs.js";
import { InlineEditTextarea } from "../inline-edit/InlineEditTextarea.js";
import { InlineEditKeyValue } from "../inline-edit/InlineEditKeyValue.js";
const OVERVIEW_TAB = { id: "overview", label: "Overview" };
const INSTANCES_TAB = { id: "instances", label: "Instances" };
const EXECUTIONS_TAB = { id: "executions", label: "Executions" };
const VERSIONS_TAB = { id: "versions", label: "Versions" };
const DESCRIPTION_COLLAPSED_HEIGHT = "8rem";
/**
 * Operational detail hub for a Workflow blueprint.
 *
 * Fetches the workflow via {@link useWorkflow} internally and renders
 * its full specification inside a {@link ResourceDetailShell}:
 *
 * - **Overview**: Description, budget, env vars, task flow DAG, document metadata
 * - **Instances**: Environment-bound deployments (embedded, not standalone)
 * - **Executions**: Recent executions with phase badges and timing
 *
 * Handles loading, error, and not-found states automatically.
 * Zero Console dependencies — safe for platform builder embedding.
 * All visual properties flow through `--stgm-*` design tokens.
 *
 * @example
 * ```tsx
 * <WorkflowDetailView org="acme" slug="onboard-user" />
 * ```
 */
export function WorkflowDetailView({ org, slug, onResourceLoad, primaryAction, actions, additionalTabs, activeTab, onTabChange, defaultTab, onExecutionClick, onCreateInstanceClick, onInstanceClick, onInstanceRunClick, onInstanceDeleteClick, instancesRefreshKey, editable = false, onResourceUpdated, onOpenInEditor, onViewLatestRun, className, }) {
    const { workflow, isLoading, error, refetch } = useWorkflow(org, slug);
    const { update, isUpdating } = useUpdateWorkflow();
    const { versions } = useWorkflowVersions(isLoading ? null : org, isLoading ? null : slug);
    const saveField = useCallback(async (field, value) => {
        if (!workflow)
            return false;
        const input = workflowToInput(workflow);
        input[field] = value;
        try {
            const updated = await update(input);
            onResourceUpdated?.(updated);
            refetch();
            return true;
        }
        catch {
            return false;
        }
    }, [workflow, update, onResourceUpdated, refetch]);
    const versionCount = versions.length;
    const builtInTabs = useMemo(() => [
        OVERVIEW_TAB,
        INSTANCES_TAB,
        EXECUTIONS_TAB,
        {
            ...VERSIONS_TAB,
            ...(versionCount > 0 && { badge: versionCount }),
        },
    ], [versionCount]);
    const { effectiveTabs, effectiveActiveTab, effectiveOnTabChange, activeAdditionalTab, } = useDetailTabs({
        builtInTabs,
        additionalTabs,
        activeTab,
        onTabChange,
        defaultTab,
    });
    const onResourceLoadRef = useRef(onResourceLoad);
    onResourceLoadRef.current = onResourceLoad;
    useEffect(() => {
        if (workflow?.metadata?.name) {
            onResourceLoadRef.current?.({
                name: workflow.metadata.name,
                id: workflow.metadata.id,
            });
        }
    }, [workflow]);
    // Unified Manage access — visibility (General access) over explicit grants
    // (People), opened from the kebab. Replaces the host's bespoke share popover.
    const access = useManageAccess({
        resource: workflow?.metadata
            ? {
                kind: ApiResourceKind.workflow,
                kindString: "workflow",
                id: workflow.metadata.id,
                org: workflow.metadata.org || org,
                name: workflow.metadata.name,
            }
            : null,
        visibility: workflow?.metadata
            ? {
                kind: "workflow",
                current: workflow.metadata.visibility,
                org: workflow.metadata.org || org,
                onChanged: refetch,
            }
            : undefined,
    });
    if (isLoading)
        return _jsx(LoadingSkeleton, { className: className });
    if (error)
        return _jsx(ErrorMessage, { error: error, retry: refetch, className: className });
    if (!workflow)
        return _jsx(NotFoundState, { className: className });
    const meta = workflow.metadata;
    const spec = workflow.spec;
    const specAudit = workflow.status?.audit?.specAudit;
    const headerMeta = {
        name: meta?.name || meta?.slug || "Untitled",
        id: meta?.id || "",
        org: meta?.org,
        slug: meta?.slug,
        description: undefined,
        icon: _jsx(WorkflowIcon, { className: "size-6 text-muted-foreground" }),
        createdAt: specAudit?.createdAt ? timestampDate(specAudit.createdAt) : null,
        updatedAt: specAudit?.updatedAt ? timestampDate(specAudit.updatedAt) : null,
    };
    const validationState = workflow.status?.serverlessWorkflowValidation?.state;
    const headerMetaExtra = validationState ? (_jsx(ValidationIndicator, { state: validationState })) : undefined;
    // Inline visibility is read-only (at-a-glance); editing lives in the
    // Manage access dialog, the single writer for both access axes.
    const visibilityControl = meta ? (_jsx(VisibilityBadge, { visibility: meta.visibility })) : undefined;
    const mergedActions = access.action
        ? [...(actions ?? []), access.action]
        : actions;
    let tabContent;
    if (activeAdditionalTab) {
        tabContent = activeAdditionalTab.content;
    }
    else if (effectiveActiveTab === "instances") {
        tabContent = (_jsx(WorkflowInstanceList, { workflowId: meta?.id ?? "", defaultInstanceId: workflow?.status?.defaultInstanceId, org: org, onCreateClick: onCreateInstanceClick, onInstanceClick: onInstanceClick, onRunClick: onInstanceRunClick, onDeleteClick: onInstanceDeleteClick, refreshKey: instancesRefreshKey }));
    }
    else if (effectiveActiveTab === "executions") {
        tabContent = (_jsx(WorkflowExecutionHistory, { org: org, workflowId: meta?.id, onExecutionClick: onExecutionClick }));
    }
    else if (effectiveActiveTab === "versions") {
        tabContent = _jsx(WorkflowVersionsTab, { workflow: workflow });
    }
    else {
        tabContent = (_jsx(OverviewTab, { workflow: workflow, org: org, editable: editable, isSaving: isUpdating, saveField: saveField, onOpenInEditor: onOpenInEditor, onViewLatestRun: onViewLatestRun, onExecutionClick: onExecutionClick }));
    }
    return (_jsxs(_Fragment, { children: [_jsx(ResourceDetailShell, { header: headerMeta, visibilityControl: visibilityControl, headerMetaExtra: headerMetaExtra, primaryAction: primaryAction, actions: mergedActions, tabs: effectiveTabs, activeTab: effectiveActiveTab, onTabChange: effectiveOnTabChange, tabsAriaLabel: "Workflow detail tabs", className: className, children: tabContent }), access.dialog] }));
}
// ---------------------------------------------------------------------------
// Tab content components
// ---------------------------------------------------------------------------
function OverviewTab({ workflow, org, editable, isSaving, saveField, onOpenInEditor, onViewLatestRun, onExecutionClick, }) {
    const spec = workflow.spec;
    const doc = spec?.document;
    const budget = spec?.budget;
    const envEntries = spec?.env ? Object.entries(spec.env) : [];
    const showDescription = editable || !!spec?.description;
    const showEnv = editable || envEntries.length > 0;
    const [envEditing, setEnvEditing] = useState(false);
    const [showExplain, setShowExplain] = useState(false);
    const [graphExpanded, setGraphExpanded] = useState(false);
    const workflowYaml = useMemo(() => {
        try {
            return serializeWorkflowYaml(workflow);
        }
        catch {
            return "";
        }
    }, [workflow]);
    const workflowId = workflow.metadata?.id;
    const { summary, isLoading: summaryLoading } = useWorkflowDashboardSummary({
        org,
        workflowId: workflowId || undefined,
    });
    const { executions } = useWorkflowExecutionList({
        workflowId,
        pageSize: 1,
    });
    const latestExecId = executions[0]?.metadata?.id;
    const handleEnvSave = useCallback(async (rows) => {
        const env = {};
        for (const row of rows) {
            if (row.key.trim()) {
                env[row.key.trim()] = {
                    isSecret: row.isSecret || undefined,
                    description: row.description || undefined,
                    optional: row.optional || undefined,
                };
            }
        }
        return saveField?.("env", Object.keys(env).length > 0 ? env : undefined) ?? false;
    }, [saveField]);
    const envRows = useMemo(() => Object.entries(spec?.env ?? {})
        .sort(([a], [b]) => a.localeCompare(b))
        .map(([key, decl]) => ({
        key,
        value: "",
        isSecret: decl.isSecret,
        description: decl.description,
        optional: decl.optional,
    })), [spec?.env]);
    return (_jsxs("div", { className: "flex flex-col gap-6", children: [_jsx(WorkflowOverviewSummary, { summary: summary, isLoading: summaryLoading }), (spec?.tasks?.length ?? 0) > 0 && (_jsxs(_Fragment, { children: [_jsx(Section, { title: "Task Flow", count: spec?.tasks?.length, headerActions: _jsx(ExpandButton, { onClick: () => setGraphExpanded(true) }), children: _jsx("div", { className: "h-[28rem]", children: _jsx(WorkflowOverviewGraph, { workflow: workflow, onOpenInEditor: onOpenInEditor, className: "h-full w-full rounded-sm bg-[var(--stgm-muted-subtle,#fafafa)]" }) }) }), _jsx(WorkflowGraphFullscreenDialog, { workflow: workflow, open: graphExpanded, onClose: () => setGraphExpanded(false), onOpenInEditor: onOpenInEditor })] })), _jsxs("div", { className: "flex flex-wrap items-center gap-3", children: [onOpenInEditor && (_jsx(QuickActionButton, { label: "Edit workflow", onClick: () => onOpenInEditor(""), icon: _jsx(EditIcon, {}) })), latestExecId && onViewLatestRun && (_jsx(QuickActionButton, { label: "View latest run", onClick: () => onViewLatestRun(latestExecId), icon: _jsx(PlayIcon, {}) })), latestExecId && !onViewLatestRun && onExecutionClick && (_jsx(QuickActionButton, { label: "View latest run", onClick: () => onExecutionClick(latestExecId), icon: _jsx(PlayIcon, {}) })), workflowYaml && (_jsx(QuickActionButton, { label: "What does this workflow do?", onClick: () => setShowExplain(true), icon: _jsx(ExplainQuestionIcon, {}) }))] }), workflowYaml && (_jsx(WorkflowExplainDialog, { open: showExplain, onOpenChange: setShowExplain, org: org, currentYaml: workflowYaml })), showDescription && (_jsx(Section, { title: "Description", children: editable ? (_jsx("div", { className: "max-h-20 overflow-y-auto p-3", children: _jsx(InlineEditTextarea, { value: spec?.description || "", onSave: (v) => saveField?.("description", v || undefined) ?? Promise.resolve(false), isSaving: isSaving, placeholder: "Add a description", minRows: 2 }) })) : (_jsx(DescriptionContent, { text: spec?.description ?? "" })) })), budget && hasBudget(budget) && (_jsx(Section, { title: "Budget", children: _jsxs("div", { className: "divide-y divide-border", children: [budget.maxCostMicros > 0 && (_jsx(MetadataRow, { label: "Max Cost", value: `$${(Number(budget.maxCostMicros) / 1_000_000).toFixed(2)}` })), budget.maxTotalTokens > 0 && (_jsx(MetadataRow, { label: "Max Tokens", value: Number(budget.maxTotalTokens).toLocaleString() })), budget.maxDurationSeconds > 0 && (_jsx(MetadataRow, { label: "Max Duration", value: formatDurationSec(budget.maxDurationSeconds) }))] }) })), showEnv && (_jsx(Section, { title: "Environment Variables", count: envEntries.length, onEdit: editable ? () => setEnvEditing((v) => !v) : undefined, children: editable ? (_jsx(InlineEditKeyValue, { value: envRows, onSave: handleEnvSave, isSaving: isSaving, editing: envEditing, onEditingChange: setEnvEditing, showSecretToggle: true, showOptionalToggle: true, showDescription: true, keyLabel: "Variable name" })) : (_jsx("div", { className: "divide-y divide-border", children: envEntries.map(([key, decl]) => (_jsxs("div", { className: "flex items-center gap-3 px-4 py-2.5", children: [_jsx("code", { className: "shrink-0 text-xs font-medium text-foreground", children: key }), !decl.optional && (_jsx("span", { className: "shrink-0 rounded bg-destructive/10 px-1 py-0.5 text-[10px] font-medium text-destructive", children: "required" })), decl.description && (_jsx("span", { className: "truncate text-xs text-muted-foreground", children: decl.description }))] }, key))) })) })), doc && (_jsx(Section, { title: "Document", children: _jsxs("div", { className: "flex flex-wrap gap-x-6 gap-y-1 px-4 py-2.5 text-xs text-muted-foreground", children: [_jsxs("span", { children: ["DSL ", doc.dsl] }), _jsx("span", { children: doc.namespace }), _jsxs("span", { children: ["v", doc.version] })] }) }))] }));
}
function QuickActionButton({ label, onClick, icon, }) {
    return (_jsxs("button", { type: "button", onClick: onClick, className: cn("inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium", "border border-[var(--stgm-border,#d4d4d8)] bg-[var(--stgm-background,#fff)]", "text-[var(--stgm-foreground,#1a1a2e)]", "hover:bg-[var(--stgm-accent,#f5f5f5)]", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--stgm-ring,#6366f1)]", "transition-colors"), children: [icon, label] }));
}
function EditIcon() {
    return (_jsx("svg", { width: "12", height: "12", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: _jsx("path", { d: "M11.5 1.5l3 3L5 14H2v-3L11.5 1.5z" }) }));
}
function PlayIcon() {
    return (_jsx("svg", { width: "12", height: "12", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: _jsx("polygon", { points: "5,3 13,8 5,13" }) }));
}
function ExplainQuestionIcon() {
    return (_jsxs("svg", { width: "12", height: "12", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: [_jsx("circle", { cx: "8", cy: "8", r: "6.5" }), _jsx("path", { d: "M6.5 6a1.5 1.5 0 1 1 1.5 1.5V9" }), _jsx("circle", { cx: "8", cy: "11.5", r: "0.5", fill: "currentColor" })] }));
}
function ExpandButton({ onClick }) {
    return (_jsx("button", { type: "button", onClick: onClick, "aria-label": "Expand task flow", className: cn("inline-flex size-6 items-center justify-center rounded-md text-muted-foreground", "hover:bg-accent-hover hover:text-foreground", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", "transition-colors"), children: _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("polyline", { points: "10,2 14,2 14,6" }), _jsx("polyline", { points: "6,14 2,14 2,10" }), _jsx("line", { x1: "14", y1: "2", x2: "9.5", y2: "6.5" }), _jsx("line", { x1: "2", y1: "14", x2: "6.5", y2: "9.5" })] }) }));
}
function DescriptionContent({ text }) {
    const [expanded, setExpanded] = useState(false);
    const contentRef = useRef(null);
    const [overflows, setOverflows] = useState(false);
    useEffect(() => {
        const el = contentRef.current;
        if (!el)
            return;
        setOverflows(el.scrollHeight > el.clientHeight);
    }, [text]);
    return (_jsxs("div", { className: "relative p-3", children: [_jsx("pre", { ref: contentRef, className: cn("whitespace-pre-wrap break-words text-sm text-foreground font-sans overflow-y-auto transition-[max-height] duration-200", !expanded && "overflow-hidden"), style: { maxHeight: expanded ? "none" : DESCRIPTION_COLLAPSED_HEIGHT }, children: text }), !expanded && overflows && (_jsx("div", { className: "pointer-events-none absolute inset-x-3 bottom-10 h-8 bg-gradient-to-t from-background to-transparent" })), overflows && (_jsx("button", { type: "button", onClick: () => setExpanded((v) => !v), className: "mt-2 text-xs font-medium text-primary transition-colors hover:text-primary-muted", children: expanded ? "Show less" : "Show more" }))] }));
}
// ---------------------------------------------------------------------------
// Validation indicator
// ---------------------------------------------------------------------------
function ValidationIndicator({ state }) {
    const config = VALIDATION_STATE_CONFIG[state];
    if (!config)
        return null;
    return (_jsxs(_Fragment, { children: [_jsx(Dot, {}), _jsx("span", { className: cn("text-xs", config.colorClass), children: config.label })] }));
}
const VALIDATION_STATE_CONFIG = {
    [ValidationState.VALID]: { label: "Valid", colorClass: "text-success" },
    [ValidationState.INVALID]: { label: "Invalid", colorClass: "text-destructive" },
    [ValidationState.PENDING]: { label: "Validating…", colorClass: "text-muted-foreground" },
    [ValidationState.FAILED]: { label: "Validation Error", colorClass: "text-destructive" },
};
// ---------------------------------------------------------------------------
// Shared utilities
// ---------------------------------------------------------------------------
function MetadataRow({ label, value, }) {
    return (_jsxs("div", { className: "flex items-center gap-3 px-4 py-2.5", children: [_jsx("span", { className: "w-28 shrink-0 text-xs text-muted-foreground", children: label }), _jsx("span", { className: "text-sm text-foreground", children: value })] }));
}
function Dot() {
    return (_jsx("span", { className: "shrink-0", "aria-hidden": "true", children: "\u00B7" }));
}
function hasBudget(budget) {
    return (Number(budget.maxCostMicros ?? 0) > 0 ||
        Number(budget.maxTotalTokens ?? 0) > 0 ||
        (budget.maxDurationSeconds ?? 0) > 0);
}
// ---------------------------------------------------------------------------
// Loading & empty states
// ---------------------------------------------------------------------------
function LoadingSkeleton({ className }) {
    return (_jsxs("div", { className: cn("flex flex-col gap-6", className), children: [_jsx("div", { className: "flex items-start gap-3", children: _jsx("div", { className: "h-8 w-48 animate-pulse rounded bg-muted" }) }), _jsx("div", { className: "h-40 animate-pulse rounded-lg bg-muted" }), _jsx("div", { className: "h-28 animate-pulse rounded-lg bg-muted" })] }));
}
function TabLoadingSkeleton() {
    return (_jsxs("div", { className: "flex flex-col gap-2", children: [_jsx("div", { className: "h-8 w-full animate-pulse rounded bg-muted" }), _jsx("div", { className: "h-8 w-full animate-pulse rounded bg-muted" }), _jsx("div", { className: "h-8 w-3/4 animate-pulse rounded bg-muted" })] }));
}
function NotFoundState({ className }) {
    return (_jsxs("div", { className: cn("flex flex-col items-center justify-center py-16", className), children: [_jsx(WorkflowIcon, { className: "size-10 text-muted-foreground-faint" }), _jsx("p", { className: "mt-2 text-sm text-muted-foreground", children: "Workflow not found" }), _jsx("p", { className: "text-xs text-muted-foreground-subtle", children: "This workflow doesn't exist or you don't have access to it." })] }));
}
// ---------------------------------------------------------------------------
// Icons — inline SVGs following the SDK pattern (no icon library dependency)
// ---------------------------------------------------------------------------
function WorkflowIcon({ className }) {
    return (_jsxs("svg", { className: className, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: [_jsx("path", { d: "M3 3h4v4H3zM9 9h4v4H9z" }), _jsx("path", { d: "M7 5h2M5 7v2M11 7V5h-2" })] }));
}
//# sourceMappingURL=WorkflowDetailView.js.map