import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { ChevronRight, Copy, Loader, RefreshCcw } from 'lucide-react';
import { useState } from 'react';
import { useLogger } from '../../hooks/useLogger';
import { cn, formatErrorForCopy, parseTokensHeader, getTotalTokens } from '../../lib/utils';
import { Action, Actions } from '../ai-elements/actions';
import { CodeBlock } from '../ai-elements/code-block';
import { Conversation, ConversationContent, ConversationScrollButton, } from '../ai-elements/conversation';
import { Message, MessageContent } from '../ai-elements/message';
import { Shimmer } from '../ai-elements/shimmer';
import { InputSection } from './input-section';
import { useWorkbench } from './workbench-provider';
export function Chat({ className, emptyState, onSchemaToggle, onSessionOpen, schemaOpen, }) {
    const { agents, clearAgentState, connectionStatus, isLoading, messages, selectedAgent, setSelectedAgent, submitMessage, } = useWorkbench();
    const logger = useLogger('Chat');
    const [value, setValue] = useState('');
    const handleSubmit = () => {
        logger.debug('🎯 Chat handleSubmit - selectedAgent:', selectedAgent, 'value:', value);
        const selectedAgentData = Object.values(agents).find((agent) => agent.metadata.agentId === selectedAgent);
        logger.debug('📊 Chat handleSubmit - selectedAgentData:', selectedAgentData);
        const hasInputSchema = selectedAgentData?.schema?.input?.json;
        logger.debug('📝 Chat handleSubmit - hasInputSchema:', hasInputSchema);
        // If agent has no input schema, submit without requiring input
        if (!hasInputSchema) {
            submitMessage('');
            return;
        }
        // For agents with input schema, require input
        if (!value.trim()) {
            return;
        }
        submitMessage(value);
        setValue('');
    };
    return (_jsxs("div", { className: cn('relative flex flex-col h-full w-full overflow-hidden', className), children: [_jsxs(Conversation, { className: "flex-1 overflow-y-auto [&>div]:overflow-y-auto", id: "chat-conversation", children: [connectionStatus === 'disconnected' && emptyState ? (_jsx("div", { className: "flex flex-col h-full", children: emptyState })) : messages.length === 0 ? (_jsx(ConversationContent, { children: _jsx("div", { className: "flex items-center justify-center h-full py-12 text-muted-foreground", children: isLoading ? (_jsx(Loader, { className: "size-5 animate-spin" })) : (_jsx("p", { className: "text-sm", children: "Send a message to get started." })) }) })) : (_jsx(ConversationContent, { children: messages.map((message) => {
                            const { role, parts, id, tokens, duration, sessionId } = message;
                            const isStreaming = parts.some((part) => part.type === 'text' && part.state === 'streaming');
                            const totalTokens = tokens
                                ? getTotalTokens(parseTokensHeader(tokens))
                                : undefined;
                            // Check for agent error in text content
                            let errorInfo;
                            const firstPart = parts[0];
                            if (parts.length === 1 && firstPart?.type === 'text') {
                                const text = firstPart.text;
                                if (text.startsWith('{') && text.includes('"__agentError"')) {
                                    try {
                                        const parsed = JSON.parse(text);
                                        if (parsed.__agentError) {
                                            errorInfo = {
                                                message: parsed.message || 'Unknown error',
                                                stack: parsed.stack,
                                                code: parsed.code,
                                                cause: parsed.cause,
                                            };
                                        }
                                    }
                                    catch {
                                        // Not valid JSON, ignore
                                    }
                                }
                            }
                            return (_jsxs("div", { className: "mb-2", children: [role === 'assistant' && (_jsxs("div", { className: "w-fit flex items-center mb-2 text-muted-foreground text-sm transition-colors", children: [_jsx(Loader, { className: cn('size-4 transition-all', isStreaming ? 'animate-spin mr-2' : 'w-0 mr-2.5') }), isStreaming ? (_jsx(Shimmer, { duration: 1, children: "Running..." })) : (_jsxs("button", { type: "button", className: cn('flex items-center bg-transparent border-none p-0 text-inherit', sessionId && onSessionOpen
                                                    ? 'hover:text-foreground transition-colors cursor-pointer'
                                                    : 'cursor-default'), onClick: () => sessionId && onSessionOpen?.(sessionId), tabIndex: 0, "aria-label": "Open session", disabled: !sessionId, style: { background: 'none' }, children: [duration ? (_jsxs(_Fragment, { children: ["Ran for", _jsx("span", { className: "mx-1", children: duration })] })) : (_jsx(_Fragment, { children: "Finished" })), duration &&
                                                        totalTokens !== undefined &&
                                                        totalTokens > 0 && (_jsxs(_Fragment, { children: ["and consumed", _jsx("span", { className: "mx-1", children: totalTokens }), "tokens"] })), sessionId && onSessionOpen && (_jsx(ChevronRight, { className: "size-4" }))] }))] })), (role === 'user' || !isStreaming) && (_jsxs(_Fragment, { children: [_jsx(Message, { from: role, className: "p-0", children: _jsx(MessageContent, { className: cn(errorInfo && 'bg-destructive/10'), children: errorInfo ? (errorInfo.stack ? (_jsx("pre", { className: "font-mono whitespace-pre-wrap overflow-x-auto text-destructive", children: errorInfo.stack })) : (_jsx("p", { className: "font-mono whitespace-pre-wrap overflow-x-auto text-destructive", children: errorInfo.message || 'Unknown error' }))) : (parts.map((part, index) => {
                                                        switch (part.type) {
                                                            case 'text':
                                                                // json?
                                                                if (part.text.startsWith('{') &&
                                                                    part.text.endsWith('}')) {
                                                                    try {
                                                                        const json = JSON.parse(part.text);
                                                                        // json!
                                                                        return (_jsx(CodeBlock
                                                                        // biome-ignore lint/suspicious/noArrayIndexKey: message parts have no stable unique id
                                                                        , { code: JSON.stringify(json, null, 2), language: "json", className: "bg-transparent border-0 [&>div>div>pre]:bg-transparent! [&_pre]:p-0!" }, `${id}-${part.text}-${index}`));
                                                                    }
                                                                    catch (_error) {
                                                                        // not json :(
                                                                        return (_jsx("div", { children: part.text || '' }, `${id}-${part.text}-${index}`));
                                                                    }
                                                                }
                                                                // text/markdown
                                                                return (
                                                                // biome-ignore lint/suspicious/noArrayIndexKey: message parts have no stable unique id
                                                                _jsx("div", { children: part.text || '' }, `${id}-${part.text}-${index}`));
                                                            default:
                                                                return null;
                                                        }
                                                    })) }) }, id), _jsxs(Actions, { className: cn('mt-1 gap-0', role === 'user' && 'justify-end'), children: [role === 'user' && (_jsx(Action, { tooltip: "Re-run", label: "Re-run", className: "size-8 hover:bg-transparent!", onClick: () => setValue(parts
                                                            .filter((part) => part.type === 'text')
                                                            .map((part) => part.text)
                                                            .join('')), children: _jsx(RefreshCcw, { className: "size-4" }) })), _jsx(Action, { tooltip: "Copy to clipboard", label: "Copy to clipboard", className: "size-8 hover:bg-transparent!", onClick: () => {
                                                            const text = errorInfo
                                                                ? formatErrorForCopy(errorInfo)
                                                                : parts
                                                                    .filter((part) => part.type === 'text')
                                                                    .map((part) => part.text)
                                                                    .join('');
                                                            navigator.clipboard.writeText(text);
                                                        }, children: _jsx(Copy, { className: "size-4" }) })] })] }))] }, id));
                        }) })), _jsx(ConversationScrollButton, {})] }), _jsx(InputSection, { agents: agents, clearAgentState: clearAgentState, isLoading: isLoading, isSchemaOpen: schemaOpen, onChange: setValue, onSchemaToggle: onSchemaToggle, onSubmit: handleSubmit, selectedAgent: selectedAgent, setSelectedAgent: setSelectedAgent, value: value })] }));
}
export default Chat;
//# sourceMappingURL=chat.js.map