"use client";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useCallback, useEffect, useRef, useState } from "react";
import { cn } from "@stigmer/theme";
import { useWorkflowArchitectFlow, } from "./useWorkflowArchitectFlow";
import { MessageThread } from "../execution/MessageThread";
import { WorkflowDiffGraph } from "./WorkflowDiffGraph";
/**
 * Three-phase dialog for generating a workflow via the Workflow Architect agent.
 *
 * **Phase 1 (Input)**: The user describes the workflow they want.
 *
 * **Phase 2 (Streaming)**: The agent works in real-time — querying task kinds,
 * validating YAML, iterating on the design. Messages and tool calls stream
 * into a `MessageThread` inside the dialog.
 *
 * **Phase 3 (Result)**: The validated YAML is extracted from the agent's
 * response, shown in a read-only preview alongside the agent's explanation.
 * The user can create the workflow, try again, or close.
 *
 * Uses the same `<dialog>` + `showModal()` pattern as `WorkflowRunDialog`.
 * Styled via `--stgm-*` design tokens (DD-005).
 *
 * @example
 * ```tsx
 * <WorkflowArchitectDialog
 *   open={showDialog}
 *   onOpenChange={setShowDialog}
 *   org="acme"
 *   onSuccess={(org, slug) => router.push(`/library/workflows/${org}/${slug}`)}
 *   onError={(msg) => toast.error(msg)}
 * />
 * ```
 */
export function WorkflowArchitectDialog({ open, onOpenChange, org, onSuccess, onError, }) {
    const dialogRef = useRef(null);
    const handleSuccess = useCallback((successOrg, slug) => {
        onOpenChange(false);
        onSuccess(successOrg, slug);
    }, [onOpenChange, onSuccess]);
    const flow = useWorkflowArchitectFlow({
        org,
        onSuccess: handleSuccess,
        onError,
    });
    useEffect(() => {
        const dialog = dialogRef.current;
        if (!dialog)
            return;
        if (open && !dialog.open) {
            flow.reset();
            dialog.showModal();
        }
        else if (!open && dialog.open) {
            dialog.close();
        }
    }, [open, flow.reset]);
    const handleDialogCancel = useCallback((e) => {
        e.preventDefault();
        onOpenChange(false);
    }, [onOpenChange]);
    const handleBackdropClick = useCallback((e) => {
        if (e.target === dialogRef.current) {
            onOpenChange(false);
        }
    }, [onOpenChange]);
    const isWorking = flow.phase === "starting" ||
        flow.phase === "streaming" ||
        flow.phase === "applying";
    return (_jsx("dialog", { ref: dialogRef, onCancel: handleDialogCancel, onClick: handleBackdropClick, className: cn("fixed inset-0 z-50 m-auto w-full max-w-3xl rounded-lg border border-border bg-popover p-0 text-popover-foreground shadow-lg", "backdrop:bg-black/50", "open:animate-in open:fade-in-0 open:zoom-in-95"), children: _jsx("div", { className: "flex flex-col", children: _jsx(DialogPhase, { flow: flow, onClose: () => onOpenChange(false) }) }) }));
}
function DialogPhase({ flow, onClose }) {
    switch (flow.phase) {
        case "idle":
            return _jsx(InputPhase, { flow: flow, onClose: onClose });
        case "starting":
        case "streaming":
            return _jsx(StreamingPhase, { flow: flow, onClose: onClose });
        case "complete":
            return _jsx(ResultPhase, { flow: flow, onClose: onClose });
        case "extraction-failed":
        case "error":
            return _jsx(ErrorPhase, { flow: flow, onClose: onClose });
        case "applying":
            return _jsx(ResultPhase, { flow: flow, onClose: onClose });
        default:
            return null;
    }
}
// ---------------------------------------------------------------------------
// Phase 1: Input
// ---------------------------------------------------------------------------
const INPUT_CLASSES = cn("w-full rounded-md border border-input bg-background px-2.5 py-1.5 text-sm text-foreground", "placeholder:text-muted-foreground", "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring", "disabled:pointer-events-none disabled:opacity-50");
function InputPhase({ flow, onClose, }) {
    return (_jsxs(_Fragment, { children: [_jsxs("div", { className: "border-b border-border px-6 py-4", children: [_jsx("h3", { className: "text-base font-semibold text-foreground", children: "Generate Workflow" }), _jsx("p", { className: "mt-0.5 text-xs text-muted-foreground", children: "Describe what you want and the Workflow Architect agent will design, validate, and generate a workflow definition" })] }), _jsxs("div", { className: "max-h-[60vh] overflow-y-auto px-6 py-4", children: [flow.error && (_jsx("div", { className: "mb-4 rounded-md border border-destructive bg-destructive-muted px-3 py-2 text-sm text-destructive", role: "alert", children: flow.error })), _jsxs("div", { className: "flex flex-col gap-1", children: [_jsxs("label", { htmlFor: "architect-prompt", className: "text-xs font-medium text-foreground", children: ["Description", _jsx("span", { className: "ml-1 text-destructive", "aria-label": "required", children: "*" })] }), _jsx("textarea", { id: "architect-prompt", value: flow.prompt, onChange: (e) => flow.setPrompt(e.target.value), placeholder: "e.g., A workflow that enriches customer data using my data-agent, validates the output, and sends a Slack notification on failure", rows: 5, className: cn(INPUT_CLASSES, "resize-y"), onKeyDown: (e) => {
                                    if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
                                        e.preventDefault();
                                        flow.generate();
                                    }
                                } }), _jsx("p", { className: "text-[0.7rem] text-muted-foreground", children: "Describe the goal, steps, and any specific agents or task kinds to use. The agent will discover available resources automatically." })] })] }), _jsxs("div", { className: "flex justify-end gap-2 border-t border-border px-6 py-3", children: [_jsx("button", { type: "button", onClick: onClose, className: cn("rounded-md px-3 py-1.5 text-sm font-medium transition-colors", "border border-input bg-background text-foreground", "hover:bg-accent hover:text-accent-foreground", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"), children: "Cancel" }), _jsx("button", { type: "button", onClick: flow.generate, disabled: flow.prompt.trim().length < 10, className: cn("inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium transition-colors", "bg-primary text-primary-foreground hover:bg-primary-hover", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", "disabled:pointer-events-none disabled:opacity-40"), children: "Generate" })] })] }));
}
// ---------------------------------------------------------------------------
// Phase 2: Streaming
// ---------------------------------------------------------------------------
function StreamingPhase({ flow, onClose, }) {
    return (_jsxs(_Fragment, { children: [_jsxs("div", { className: "border-b border-border px-6 py-4", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx("h3", { className: "text-base font-semibold text-foreground", children: "Workflow Architect" }), _jsxs("span", { className: "inline-flex items-center gap-1.5 text-xs text-muted-foreground", children: [_jsx(SpinnerIcon, {}), flow.phase === "starting" ? "Starting…" : "Working…"] })] }), _jsx("p", { className: "mt-0.5 text-xs text-muted-foreground", children: "The agent is designing and validating your workflow" })] }), _jsx("div", { className: "h-[55vh] overflow-hidden", children: _jsx(MessageThread, { executions: [], activeStreamExecution: flow.execution, pendingUserMessage: flow.phase === "starting" ? flow.prompt : undefined, className: "h-full" }) }), _jsx("div", { className: "flex justify-end gap-2 border-t border-border px-6 py-3", children: _jsx("button", { type: "button", onClick: () => {
                        flow.reset();
                        onClose();
                    }, className: cn("rounded-md px-3 py-1.5 text-sm font-medium transition-colors", "border border-input bg-background text-foreground", "hover:bg-accent hover:text-accent-foreground", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"), children: "Cancel" }) })] }));
}
// ---------------------------------------------------------------------------
// Phase 3: Result
// ---------------------------------------------------------------------------
function ResultPhase({ flow, onClose, }) {
    const isApplying = flow.phase === "applying";
    const [showYaml, setShowYaml] = useState(false);
    return (_jsxs(_Fragment, { children: [_jsxs("div", { className: "border-b border-border px-6 py-4", children: [_jsx("h3", { className: "text-base font-semibold text-foreground", children: "Generated Workflow" }), _jsx("p", { className: "mt-0.5 text-xs text-muted-foreground", children: "Review the generated workflow before creating it" })] }), _jsxs("div", { className: "max-h-[65vh] overflow-y-auto px-6 py-4", children: [flow.error && (_jsx("div", { className: "mb-4 rounded-md border border-destructive bg-destructive-muted px-3 py-2 text-sm text-destructive", role: "alert", children: flow.error })), flow.explanation && (_jsxs("div", { className: "mb-4", children: [_jsx("h4", { className: "mb-1 text-xs font-medium text-muted-foreground", children: "Explanation" }), _jsx("p", { className: "whitespace-pre-wrap text-sm text-foreground", children: flow.explanation })] })), flow.extractedYaml && (_jsxs("div", { children: [_jsx("h4", { className: "mb-1 text-xs font-medium text-muted-foreground", children: "Workflow Structure" }), _jsx("div", { className: "h-[280px] overflow-hidden rounded-md border border-border", children: _jsx(WorkflowDiffGraph, { beforeYaml: "", afterYaml: flow.extractedYaml }) }), _jsxs("div", { className: "mt-3", children: [_jsx("button", { type: "button", onClick: () => setShowYaml((v) => !v), className: "text-xs font-medium text-muted-foreground hover:text-foreground", children: showYaml ? "▾ Hide YAML" : "▸ View YAML" }), showYaml && (_jsx("pre", { className: "mt-1 max-h-60 overflow-auto rounded-md border border-border bg-muted p-3 text-xs leading-relaxed text-foreground", children: flow.extractedYaml }))] })] }))] }), _jsxs("div", { className: "flex justify-between border-t border-border px-6 py-3", children: [_jsx("button", { type: "button", onClick: onClose, disabled: isApplying, className: cn("rounded-md px-3 py-1.5 text-sm font-medium transition-colors", "text-muted-foreground hover:text-foreground", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", "disabled:pointer-events-none disabled:opacity-50"), children: "Close" }), _jsxs("div", { className: "flex gap-2", children: [_jsx("button", { type: "button", onClick: flow.reset, disabled: isApplying, className: cn("rounded-md px-3 py-1.5 text-sm font-medium transition-colors", "border border-input bg-background text-foreground", "hover:bg-accent hover:text-accent-foreground", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", "disabled:pointer-events-none disabled:opacity-50"), children: "Try Again" }), _jsxs("button", { type: "button", onClick: flow.createWorkflow, disabled: isApplying, className: cn("inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium transition-colors", "bg-primary text-primary-foreground hover:bg-primary-hover", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", "disabled:pointer-events-none disabled:opacity-40"), children: [isApplying && _jsx(SpinnerIcon, {}), isApplying ? "Creating…" : "Create Workflow"] })] })] })] }));
}
// ---------------------------------------------------------------------------
// Error / extraction-failed phase
// ---------------------------------------------------------------------------
function ErrorPhase({ flow, onClose, }) {
    return (_jsxs(_Fragment, { children: [_jsx("div", { className: "border-b border-border px-6 py-4", children: _jsx("h3", { className: "text-base font-semibold text-foreground", children: "Generation Failed" }) }), _jsx("div", { className: "px-6 py-6", children: _jsx("div", { className: "rounded-md border border-destructive bg-destructive-muted px-3 py-2 text-sm text-destructive", role: "alert", children: flow.error ?? "An unexpected error occurred." }) }), _jsxs("div", { className: "flex justify-end gap-2 border-t border-border px-6 py-3", children: [_jsx("button", { type: "button", onClick: onClose, className: cn("rounded-md px-3 py-1.5 text-sm font-medium transition-colors", "border border-input bg-background text-foreground", "hover:bg-accent hover:text-accent-foreground", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"), children: "Close" }), _jsx("button", { type: "button", onClick: flow.reset, className: cn("inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium transition-colors", "bg-primary text-primary-foreground hover:bg-primary-hover", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"), children: "Try Again" })] })] }));
}
// ---------------------------------------------------------------------------
// Shared components
// ---------------------------------------------------------------------------
function SpinnerIcon({ size = 14 }) {
    return (_jsx("svg", { width: size, height: size, 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=WorkflowArchitectDialog.js.map