import { Component } from 'react';
import { defaultEngineFactory } from './engines';
import { ErrorInfo as ErrorInfo_2 } from 'react';
import { JSX as JSX_2 } from 'react/jsx-runtime';
import { LucideIcon } from 'lucide-react';
import { ReactNode } from 'react';
import { ReactPortal } from 'react';
import { WasmEngineAdapter } from './engines';

/**
 * Audit trail entry for tracking changes (matches Rust AuditTrail)
 */
export declare interface AuditTrail {
    /** Workflow ID where change occurred */
    workflow_id: string;
    /** Task ID where change occurred */
    task_id: string;
    /** Timestamp of the change */
    timestamp: string;
    /** Changes made by the task */
    changes: Change[];
    /** Status code (e.g., 200 for success) */
    status: number;
}

/**
 * Built-in function types
 */
export declare type BuiltinFunctionType = 'map' | 'validation';

/**
 * A single change in the audit trail
 */
export declare interface Change {
    /** Path to the changed field (e.g., "data.user.name") */
    path: string;
    /** Previous value */
    old_value: unknown;
    /** New value */
    new_value: unknown;
}

/**
 * Deep clone a message
 */
export declare function cloneMessage(message: Message): Message;

export declare function ConditionBadge({ condition, className, onClick }: ConditionBadgeProps): JSX_2.Element;

declare interface ConditionBadgeProps {
    condition: JsonLogicValue | undefined;
    className?: string;
    onClick?: () => void;
}

/**
 * Result of evaluating a condition
 */
export declare interface ConditionResult {
    /** The condition that was evaluated */
    condition: JsonLogicValue;
    /** The result of evaluation */
    result: boolean;
    /** Data context used for evaluation */
    context: Record<string, unknown>;
}

/**
 * Create an empty message
 */
export declare function createEmptyMessage(): Message;

/**
 * Interface for custom dataflow engines
 *
 * Implement this interface to provide a custom WASM engine for executing
 * workflows with custom functions or plugins.
 */
export declare interface DataflowEngine {
    /**
     * Process a payload through the engine and return an execution trace
     * for step-by-step debugging.
     */
    processWithTrace(payload: Record<string, unknown>): Promise<ExecutionTrace>;
    /**
     * Optional cleanup method called when the engine is no longer needed.
     * Use this to free WASM memory.
     */
    dispose?(): void;
}

/**
 * Actions for the debugger reducer
 */
export declare type DebuggerAction = {
    type: 'ACTIVATE';
} | {
    type: 'DEACTIVATE';
} | {
    type: 'SET_INPUT_PAYLOAD';
    payload: Record<string, unknown>;
} | {
    type: 'START_EXECUTION';
} | {
    type: 'EXECUTE_TRACE';
    trace: ExecutionTrace;
} | {
    type: 'EXECUTION_ERROR';
    error: string;
} | {
    type: 'PLAY';
} | {
    type: 'PAUSE';
} | {
    type: 'STOP';
} | {
    type: 'RESET';
} | {
    type: 'STEP_FORWARD';
} | {
    type: 'STEP_BACKWARD';
} | {
    type: 'GO_TO_STEP';
    index: number;
} | {
    type: 'SET_SPEED';
    speed: number;
};

/**
 * Context value interface
 */
declare interface DebuggerContextValue {
    state: DebuggerState;
    dispatch: React.Dispatch<DebuggerAction>;
    activate: () => void;
    deactivate: () => void;
    setInputPayload: (payload: Record<string, unknown>) => void;
    executeTrace: (trace: ExecutionTrace) => void;
    startExecution: () => void;
    setExecutionError: (error: string) => void;
    play: () => void;
    pause: () => void;
    stop: () => void;
    reset: () => void;
    stepForward: () => void;
    stepBackward: () => void;
    goToStep: (index: number) => void;
    setSpeed: (speed: number) => void;
    runExecution: (workflows: Workflow[], payload: Record<string, unknown>) => Promise<ExecutionTrace | null>;
    currentStep: ExecutionStep | null;
    currentMessage: Message | null;
    currentChanges: Change[];
    isAtStart: boolean;
    isAtEnd: boolean;
    hasTrace: boolean;
    progress: number;
    totalSteps: number;
    isEngineReady: boolean;
}

/**
 * Playback controls for the debugger
 */
export declare function DebuggerControls({ compact, className }: DebuggerControlsProps): JSX_2.Element;

declare interface DebuggerControlsProps {
    /** Show compact version */
    compact?: boolean;
    /** Additional CSS class */
    className?: string;
}

/**
 * Provider component for debugger state
 */
export declare function DebuggerProvider({ children, initialPayload, autoActivate, engineFactory, }: DebuggerProviderProps): JSX_2.Element;

declare interface DebuggerProviderProps {
    children: ReactNode;
    /** Initial payload to use for debugging */
    initialPayload?: Record<string, unknown>;
    /** Auto-start in debug mode */
    autoActivate?: boolean;
    /**
     * Factory function to create engine instances when workflows change.
     * Called whenever workflows are updated to create a fresh engine.
     * Use this for custom WASM engines with plugins.
     */
    engineFactory?: EngineFactory;
}

/**
 * Complete debugger state
 */
export declare interface DebuggerState {
    /** Whether debug mode is active */
    isActive: boolean;
    /** Current execution trace */
    trace: ExecutionTrace | null;
    /** Current step index being viewed */
    currentStepIndex: number;
    /** Playback state */
    playbackState: PlaybackState;
    /** Playback speed (ms between steps) */
    playbackSpeed: number;
    /** Input payload for debugging */
    inputPayload: Record<string, unknown> | null;
    /** Whether the debugger is currently executing */
    isExecuting: boolean;
    /** Error during execution */
    executionError: string | null;
}

/**
 * Tooltip/bubble showing debug step details
 */
export declare function DebugInfoBubble({ step, targetRef, visible, onClose, }: DebugInfoBubbleProps): ReactPortal | null;

declare interface DebugInfoBubbleProps {
    /** The execution step to display */
    step: ExecutionStep;
    /** Target element to position near */
    targetRef: React.RefObject<HTMLElement>;
    /** Whether the bubble is visible */
    visible: boolean;
    /** Callback when bubble is closed */
    onClose?: () => void;
}

/**
 * Debug state for a node in the execution tree
 */
export declare type DebugNodeState = 'pending' | 'current' | 'executed' | 'skipped' | 'error';

export declare function DebugStateBadge({ state, conditionResult, size, }: DebugStateBadgeProps): JSX_2.Element;

/**
 * Small badge showing debug state on tree nodes
 */
declare interface DebugStateBadgeProps {
    state: DebugNodeState;
    conditionResult?: boolean;
    size?: 'sm' | 'md';
}

export { defaultEngineFactory }

/**
 * Factory function type for creating engine instances.
 *
 * Called when workflows change to create a new engine instance
 * configured with the current workflows.
 */
export declare type EngineFactory = (workflows: Workflow[]) => DataflowEngine;

/**
 * Error boundary component to catch and display errors in child components
 */
export declare class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
    constructor(props: ErrorBoundaryProps);
    static getDerivedStateFromError(error: Error): ErrorBoundaryState;
    componentDidCatch(error: Error, errorInfo: ErrorInfo_2): void;
    render(): ReactNode;
}

declare interface ErrorBoundaryProps {
    children: ReactNode;
    fallback?: ReactNode;
}

declare interface ErrorBoundaryState {
    hasError: boolean;
    error: Error | null;
}

/**
 * Error information captured during execution
 */
export declare interface ErrorInfo {
    /** Error code or identifier */
    code: string;
    /** Human-readable error message */
    message: string;
    /** Task ID where error occurred */
    task_id?: string;
    /** Workflow ID where error occurred */
    workflow_id?: string;
}

/**
 * A single step in the execution trace (matches Rust ExecutionStep)
 */
export declare interface ExecutionStep {
    /** ID of the workflow this step belongs to */
    workflow_id: string;
    /** ID of the task (undefined for workflow-level skips) */
    task_id?: string;
    /** Result of the step execution */
    result: StepResult;
    /** Message snapshot after this step (only for executed steps) */
    message?: Message;
}

/**
 * Complete execution trace (matches Rust ExecutionTrace)
 */
export declare interface ExecutionTrace {
    /** All execution steps in order */
    steps: ExecutionStep[];
}

/**
 * Function configuration for a task
 */
export declare interface FunctionConfig {
    /** Function name (e.g., "map", "validation", or custom) */
    name: string;
    /** Function-specific input configuration */
    input?: Record<string, unknown>;
}

export declare function FunctionTypeBadge({ functionName, className }: FunctionTypeBadgeProps): JSX_2.Element;

declare interface FunctionTypeBadgeProps {
    functionName: string;
    className?: string;
}

/**
 * Get the changes made at a specific step
 * Returns the changes from the last audit_trail entry if step was executed
 */
export declare function getChangesAtStep(trace: ExecutionTrace, stepIndex: number): Change[];

/**
 * Get display info for a function type including the Lucide icon component
 */
export declare function getFunctionDisplayInfo(name: string): {
    label: string;
    colorClass: string;
    Icon: LucideIcon;
};

/**
 * Get the message at a specific step in the trace
 * Returns the message snapshot from the last executed step at or before the given index
 */
export declare function getMessageAtStep(trace: ExecutionTrace, stepIndex: number): Message | null;

/**
 * Get the state of a task based on the trace and current step
 * Returns:
 * - 'pending' for future steps (after current)
 * - 'executed'/'skipped'/'error' for steps at or before current position
 * Note: Tasks show as 'executed' when on their step (completed state)
 */
export declare function getTaskState(trace: ExecutionTrace, currentStepIndex: number, workflowId: string, taskId: string): DebugNodeState;

/**
 * Get the state of a workflow based on the trace and current step
 * Returns:
 * - 'pending' if all workflow steps are after the current step
 * - 'executed'/'skipped'/'error' for workflows with steps at or before current
 * Note: Workflows don't show as 'current' - only individual tasks do
 */
export declare function getWorkflowState(trace: ExecutionTrace, currentStepIndex: number, workflowId: string): DebugNodeState;

/**
 * Check if a function is a built-in type
 */
export declare function isBuiltinFunction(name: string): name is BuiltinFunctionType;

/**
 * JSONLogic value type - can be any valid JSON value or JSONLogic expression
 */
export declare type JsonLogicValue = string | number | boolean | null | JsonLogicValue[] | {
    [key: string]: JsonLogicValue;
};

export declare function JsonViewer({ data, initialExpanded, maxStringLength, className, }: JsonViewerProps): JSX_2.Element;

declare interface JsonViewerProps {
    data: unknown;
    initialExpanded?: boolean;
    maxStringLength?: number;
    className?: string;
}

/**
 * Legacy execution step type (for backwards compatibility)
 * @deprecated Use ExecutionStep instead
 */
export declare interface LegacyExecutionStep {
    /** Unique ID for this step */
    id: string;
    /** Type of step */
    type: 'workflow-condition' | 'workflow-start' | 'workflow-end' | 'task-condition' | 'task-start' | 'task-end';
    /** Associated workflow */
    workflow: Workflow;
    /** Associated task (if applicable) */
    task?: Task;
    /** Result of condition evaluation (if applicable) */
    conditionResult?: ConditionResult;
    /** Message state before this step */
    messageBefore: Message;
    /** Message state after this step */
    messageAfter: Message;
    /** State of this node */
    state: DebugNodeState;
    /** Timestamp when this step occurred */
    timestamp: number;
    /** Duration of this step in ms (for task-end) */
    duration?: number;
    /** Error if this step failed */
    error?: ErrorInfo;
}

/**
 * Legacy trace type (for backwards compatibility)
 * @deprecated Use ExecutionTrace instead
 */
export declare interface LegacyWorkflowExecutionTrace {
    /** All execution steps */
    steps: LegacyExecutionStep[];
    /** Initial message before any processing */
    initialMessage: Message;
    /** Final message after all processing */
    finalMessage: Message;
    /** Total execution duration in ms */
    totalDuration: number;
    /** Whether execution completed successfully */
    success: boolean;
}

/**
 * Map function input configuration
 */
export declare interface MapFunctionInput {
    mappings: MapMapping[];
}

/**
 * Map function mapping configuration
 */
export declare interface MapMapping {
    /** Target path for the mapped value */
    path: string;
    /** JSONLogic expression to compute the value */
    logic: JsonLogicValue;
}

/**
 * Alias for MapMapping - used in tree and details views
 */
export declare type MappingItem = MapMapping;

/**
 * Message structure for workflow execution
 * Mirrors the Rust Message struct from WASM output
 */
export declare interface Message {
    /** Unique message ID */
    id: string;
    /** Original payload */
    payload: Record<string, unknown>;
    /** Context containing data, metadata, temp_data */
    context: {
        data: Record<string, unknown>;
        metadata: Record<string, unknown>;
        temp_data: Record<string, unknown>;
    };
    /** List of errors that occurred during processing */
    errors: ErrorInfo[];
    /** Audit trail of changes made during processing */
    audit_trail: AuditTrail[];
}

/**
 * Panel for inputting test payload data
 *
 * Note: This is a simplified version that works with the new ExecutionTrace-based
 * debugging system. The input is a JSON payload that gets processed through workflows.
 */
export declare function MessageInputPanel({ onExecute, isExecuting, className, }: MessageInputPanelProps): JSX_2.Element;

declare interface MessageInputPanelProps {
    /** Callback to trigger debug execution */
    onExecute: () => void;
    /** Whether execution is in progress */
    isExecuting?: boolean;
    /** Additional CSS class */
    className?: string;
}

/**
 * Panel showing message state at current execution step
 */
export declare function MessageStatePanel({ className }: MessageStatePanelProps): JSX_2.Element;

declare interface MessageStatePanelProps {
    /** Additional CSS class */
    className?: string;
}

/**
 * Playback state for the debugger
 */
export declare type PlaybackState = 'stopped' | 'playing' | 'paused';

export declare function RulesListView({ workflows, highlightedTaskIds, onTaskSelect, defaultExpandedIds, }: RulesListViewProps): JSX_2.Element;

declare interface RulesListViewProps {
    workflows: Workflow[];
    highlightedTaskIds?: Set<string>;
    onTaskSelect?: (task: Task, workflow: Workflow) => void;
    defaultExpandedIds?: string[];
}

export declare function SearchInput({ value, onChange, onClear, placeholder, className, }: SearchInputProps): JSX_2.Element;

declare interface SearchInputProps {
    value: string;
    onChange: (value: string) => void;
    onClear?: () => void;
    placeholder?: string;
    className?: string;
}

export declare type SelectionType = TreeSelectionType;

/**
 * Result of a step (executed or skipped)
 */
export declare type StepResult = 'executed' | 'skipped';

/**
 * Task definition within a workflow
 */
export declare interface Task {
    /** Unique identifier for the task */
    id: string;
    /** Human-readable name */
    name: string;
    /** Optional description */
    description?: string;
    /** JSONLogic condition (evaluated against metadata only) */
    condition?: JsonLogicValue;
    /** Function to execute */
    function: FunctionConfig;
    /** Whether to continue workflow if this task fails */
    continue_on_error?: boolean;
}

export declare function TaskRow({ task, workflow, index, isHighlighted, onSelect, }: TaskRowProps): JSX_2.Element;

declare interface TaskRowProps {
    task: Task;
    workflow: Workflow;
    index: number;
    isHighlighted?: boolean;
    onSelect?: (task: Task, workflow: Workflow) => void;
}

export declare type Theme = 'light' | 'dark' | 'system';

declare interface ThemeContextValue {
    theme: Theme;
    resolvedTheme: 'light' | 'dark';
    setTheme: (theme: Theme) => void;
}

export declare function ThemeProvider({ children, defaultTheme }: ThemeProviderProps): JSX_2.Element;

declare interface ThemeProviderProps {
    children: ReactNode;
    defaultTheme?: Theme;
}

/**
 * Result of the debug state hook for a tree node
 */
export declare interface TreeNodeDebugState {
    /** Current debug state of this node */
    state: DebugNodeState | null;
    /** Whether this node is the current step being viewed */
    isCurrent: boolean;
    /** Whether this node has been executed (or is being executed) */
    isExecuted: boolean;
    /** Whether this node was skipped due to condition */
    isSkipped: boolean;
    /** Whether this node had an error */
    hasError: boolean;
    /** Condition result if this is a condition node */
    conditionResult?: boolean;
}

export declare type TreeSelectionType = {
    type: 'none';
} | {
    type: 'workflow-condition';
    workflow: Workflow;
    condition: JsonLogicValue;
} | {
    type: 'task';
    task: Task;
    workflow: Workflow;
} | {
    type: 'task-condition';
    task: Task;
    workflow: Workflow;
    condition: JsonLogicValue;
} | {
    type: 'mapping';
    task: Task;
    workflow: Workflow;
    mapping: MappingItem;
    mappingIndex: number;
} | {
    type: 'validation-rule';
    task: Task;
    workflow: Workflow;
    rule: ValidationRule;
    ruleIndex: number;
};

export declare function TreeView({ workflows, selection, onSelect, debugMode }: TreeViewProps): JSX_2.Element;

declare interface TreeViewProps {
    workflows: Workflow[];
    selection: TreeSelectionType;
    onSelect: (selection: TreeSelectionType) => void;
    /** Enable debug mode with state indicators */
    debugMode?: boolean;
}

/**
 * Hook to access debugger context
 */
export declare function useDebugger(): DebuggerContextValue;

/**
 * Hook to check if debugger is available (doesn't throw if not in provider)
 */
export declare function useDebuggerOptional(): DebuggerContextValue | null;

/**
 * Hook to get debug state for a task condition node
 * Note: In the simplified trace format, task conditions are implicit
 * A task skip step indicates the condition was false
 */
export declare function useTaskConditionDebugState(task: Task, workflow: Workflow): TreeNodeDebugState;

/**
 * Hook to get debug state for a task node
 */
export declare function useTaskDebugState(task: Task, workflow: Workflow): TreeNodeDebugState;

export declare function useTheme(): ThemeContextValue;

/**
 * Generic hook to get debug state for any node type
 */
export declare function useTreeNodeDebugState(options: {
    type: 'workflow' | 'workflow-condition' | 'task' | 'task-condition' | 'mapping' | 'validation-rule';
    workflow: Workflow;
    task?: Task;
}): TreeNodeDebugState;

/**
 * Hook to get debug state for a workflow condition node
 * Note: In the simplified trace format, workflow conditions are implicit
 * A workflow skip step indicates the condition was false
 */
export declare function useWorkflowConditionDebugState(workflow: Workflow): TreeNodeDebugState;

/**
 * Hook to get debug state for a workflow node
 * Note: Workflows never show as 'current' - only tasks do
 */
export declare function useWorkflowDebugState(workflow: Workflow): TreeNodeDebugState;

/**
 * Validation function input configuration
 */
export declare interface ValidationFunctionInput {
    rules: ValidationRule[];
}

/**
 * Validation rule configuration
 */
export declare interface ValidationRule {
    /** JSONLogic expression that should return true for valid data */
    logic: JsonLogicValue;
    /** Error message if validation fails */
    message: string;
}

export { WasmEngineAdapter }

/**
 * Workflow definition
 */
export declare interface Workflow {
    /** Unique identifier for the workflow */
    id: string;
    /** Human-readable name */
    name: string;
    /** Execution priority (lower = higher priority, 0 is highest) */
    priority?: number;
    /** Optional description */
    description?: string;
    /** Optional folder path for grouping (e.g., "orders/processing") */
    path?: string;
    /** JSONLogic condition (evaluated against metadata only) */
    condition?: JsonLogicValue;
    /** Tasks in this workflow */
    tasks: Task[];
    /** Whether to continue processing other workflows if this one fails */
    continue_on_error?: boolean;
}

export declare function WorkflowCard({ workflow, isExpanded, onToggle, onTaskSelect, highlightedTaskIds, }: WorkflowCardProps): JSX_2.Element;

declare interface WorkflowCardProps {
    workflow: Workflow;
    isExpanded: boolean;
    onToggle: () => void;
    onTaskSelect?: (task: Workflow['tasks'][0], workflow: Workflow) => void;
    highlightedTaskIds?: Set<string>;
}

export declare function WorkflowFlowView({ workflows, onTaskSelect, onWorkflowSelect, onWorkflowConditionClick, onTaskConditionClick, selection, highlightedTaskIds, }: WorkflowFlowViewProps): JSX_2.Element;

declare interface WorkflowFlowViewProps {
    workflows: Workflow[];
    onTaskSelect?: (task: Task, workflow: Workflow) => void;
    onWorkflowSelect?: (workflow: Workflow) => void;
    onWorkflowConditionClick?: (workflow: Workflow) => void;
    onTaskConditionClick?: (task: Task, workflow: Workflow) => void;
    selection?: SelectionType;
    highlightedTaskIds?: Set<string>;
}

export declare function WorkflowVisualizer({ workflows, onWorkflowSelect, onTaskSelect, theme, className, executionResult, debugMode, }: WorkflowVisualizerProps): JSX_2.Element;

export declare interface WorkflowVisualizerProps {
    /** Array of workflow definitions to display */
    workflows: Workflow[];
    /** Callback when a workflow is selected */
    onWorkflowSelect?: (workflow: Workflow) => void;
    /** Callback when a task is selected */
    onTaskSelect?: (task: Task, workflow: Workflow) => void;
    /** Initial theme setting */
    theme?: Theme;
    /** Class name for the root element */
    className?: string;
    /** Execution result to display in the result panel */
    executionResult?: Message | null;
    /** Enable debug mode with step-by-step visualization */
    debugMode?: boolean;
}

export { }
