import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { ArrowUp, Braces, CheckIcon, ChevronDownIcon, ChevronsUpDownIcon, ListPlus, Loader2Icon, SendIcon, Sparkles, SquareCode, Trash2, } from 'lucide-react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { convertJsonSchemaToZod } from 'zod-from-json-schema';
import { useLogger } from '../../hooks/useLogger';
import { cn, generateTemplateFromSchema } from '../../lib/utils';
import { PromptInput, PromptInputBody, PromptInputFooter, PromptInputTextarea, } from '../ai-elements/prompt-input';
import { Button } from '../ui/button';
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, } from '../ui/command';
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
import { Tooltip, TooltipContent, TooltipTrigger } from '../ui/tooltip';
import { JsonEditor } from './json-editor';
import { useWorkbench } from './workbench-provider';
function isSchemaRootObject(schemaJson) {
    if (!schemaJson)
        return false;
    try {
        return (schemaJson.type === 'object' ||
            (schemaJson.type === undefined && schemaJson.properties !== undefined));
    }
    catch {
        return false;
    }
}
export function InputSection({ agents, className, clearAgentState, isLoading, isSchemaOpen, onChange, onSchemaToggle, onSubmit, selectedAgent, setSelectedAgent, value, }) {
    const logger = useLogger('InputSection');
    const { generateSample, isGeneratingSample, env, portals } = useWorkbench();
    const isAuthenticated = env.authenticated;
    const [agentSelectOpen, setAgentSelectOpen] = useState(false);
    const [prefillOpen, setPrefillOpen] = useState(false);
    const [isValidInput, setIsValidInput] = useState(true);
    const [monacoHasErrors, setMonacoHasErrors] = useState(null);
    const selectedAgentData = Object.values(agents).find((agent) => agent.metadata.agentId === selectedAgent);
    // Determine input type for switch case
    const inputType = useMemo(() => {
        const schema = selectedAgentData?.schema?.input?.json;
        logger.debug('🎛️ InputSection - selectedAgent:', selectedAgent, 'selectedAgentData:', selectedAgentData, 'schema:', schema);
        if (!schema) {
            return 'none'; // Agent has no input schema
        }
        if (isSchemaRootObject(schema)) {
            return 'object'; // Complex object schema
        }
        if (schema.type === 'string') {
            return 'string'; // String schema
        }
        return 'none'; // Default to none for other types
    }, [selectedAgentData, logger, selectedAgent]);
    const isObjectSchema = inputType === 'object';
    // Validate JSON input against schema using zod (fallback for non-Monaco cases)
    const validateInput = useCallback((inputValue, schema) => {
        if (!schema || !isObjectSchema || !inputValue.trim()) {
            return true; // No validation needed or empty input
        }
        try {
            // Parse JSON first
            const parsedJson = JSON.parse(inputValue);
            // Convert schema to zod and validate
            const schemaObject = typeof schema === 'string' ? JSON.parse(schema) : schema;
            const zodSchema = convertJsonSchemaToZod(schemaObject);
            // Validate with zod
            const result = zodSchema.safeParse(parsedJson);
            return result.success;
        }
        catch {
            // JSON parse error or schema validation error
            return false;
        }
    }, [isObjectSchema]);
    // Reset Monaco error state when schema changes
    // biome-ignore lint/correctness/useExhaustiveDependencies: Trigger on schema change
    useEffect(() => {
        if (isObjectSchema) {
            setMonacoHasErrors(null);
        }
    }, [selectedAgentData, isObjectSchema]);
    // Update validation state - use Monaco errors if available, otherwise fall back to zod validation
    useEffect(() => {
        if (isObjectSchema) {
            if (monacoHasErrors !== null) {
                // Monaco is handling validation, use its error state
                setIsValidInput(!monacoHasErrors);
            }
            else {
                // Monaco hasn't reported yet, use zod validation as fallback
                const isValid = validateInput(value, selectedAgentData?.schema?.input?.json);
                setIsValidInput(isValid);
            }
        }
        else {
            // No schema or not object schema
            setIsValidInput(true);
        }
    }, [
        value,
        selectedAgentData?.schema?.input?.json,
        validateInput,
        isObjectSchema,
        monacoHasErrors,
    ]);
    const handleGenerateSample = async () => {
        if (!selectedAgentData?.schema.input?.json || !isObjectSchema || !selectedAgent)
            return;
        try {
            const sampleJson = await generateSample(selectedAgent);
            onChange(sampleJson);
        }
        catch (error) {
            logger.error('Failed to generate sample JSON:', error);
        }
    };
    // Memoized submit disabled condition for readability
    const isSubmitDisabled = useMemo(() => {
        if (isLoading) {
            return true;
        }
        if (inputType === 'string' && !value.trim()) {
            return true;
        }
        if (inputType === 'object' && (!isValidInput || !value.trim())) {
            return true;
        }
        return false;
    }, [isLoading, inputType, value, isValidInput]);
    return (_jsxs("div", { className: cn('flex flex-col gap-4 p-4 z-100', className), children: [_jsxs("div", { className: "flex items-center gap-2", children: [portals?.actionBar?.pre, _jsxs(Popover, { open: agentSelectOpen, onOpenChange: setAgentSelectOpen, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsxs(Button, { "aria-expanded": agentSelectOpen, variant: "outline", size: "sm", className: "font-normal bg-background dark:bg-background hover:bg-background dark:hover:bg-background dark:hover:border-border/70", children: [Object.values(agents).find((agent) => agent.metadata.agentId === selectedAgent)?.metadata.name || 'Select Agent', _jsx(ChevronsUpDownIcon, { className: "size-4 shrink-0 opacity-50" })] }) }), _jsx(PopoverContent, { side: "top", align: "start", className: "w-fit p-0 z-101", children: _jsxs(Command, { children: [_jsx(CommandInput, { placeholder: "Search agents..." }), _jsxs(CommandList, { children: [_jsx(CommandEmpty, { children: "No agents found." }), Object.values(agents).length > 0 && (_jsx(CommandGroup, { children: Object.values(agents)
                                                        .sort((a, b) => a.metadata.name.localeCompare(b.metadata.name))
                                                        .map((agent) => {
                                                        const isSelected = selectedAgent === agent.metadata.agentId;
                                                        // Use name for search but include agentId to ensure uniqueness
                                                        const searchValue = `${agent.metadata.name}|${agent.metadata.agentId}`;
                                                        return (_jsxs(CommandItem, { value: searchValue, onSelect: (currentValue) => {
                                                                // Extract agentId from the compound value
                                                                const agentId = currentValue.split('|')[1];
                                                                if (!agentId) {
                                                                    setAgentSelectOpen(false);
                                                                    return;
                                                                }
                                                                const selectedAgentData = Object.values(agents).find((a) => a.metadata.agentId === agentId);
                                                                if (selectedAgentData) {
                                                                    logger.debug('🎯 Agent selected by name:', agent.metadata.name, 'agentId:', agentId);
                                                                    setSelectedAgent(agentId);
                                                                }
                                                                setAgentSelectOpen(false);
                                                            }, children: [_jsx(CheckIcon, { className: cn('size-4 text-green-500', isSelected ? 'opacity-100' : 'opacity-0') }), agent.metadata.name] }, agent.metadata.agentId));
                                                    }) }))] })] }) })] }), onSchemaToggle && (_jsxs(Button, { "aria-label": isSchemaOpen ? 'Hide Schema' : 'View Schema', size: "sm", variant: "outline", className: cn('font-normal bg-background dark:bg-background hover:bg-background dark:hover:bg-background dark:hover:border-border/50', isSchemaOpen && 'bg-secondary!'), onClick: onSchemaToggle, children: [_jsx(Braces, { className: "size-4" }), "Schema"] })), isObjectSchema && (_jsxs(Popover, { open: prefillOpen, onOpenChange: setPrefillOpen, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsxs(Button, { "aria-expanded": prefillOpen, "aria-label": "Pre-fill input", size: "sm", variant: "outline", className: "font-normal bg-background dark:bg-background hover:bg-background dark:hover:bg-background dark:hover:border-border/70", children: [_jsx(ListPlus, { className: "size-4" }), "Pre-fill", _jsx(ChevronDownIcon, { className: "size-4 shrink-0 opacity-50" })] }) }), _jsx(PopoverContent, { side: "top", align: "start", className: "w-fit max-w-xl p-0 z-101", children: _jsx(Command, { children: _jsx(CommandList, { children: _jsxs(CommandGroup, { children: [_jsxs(CommandItem, { onSelect: () => {
                                                        const template = generateTemplateFromSchema(selectedAgentData?.schema?.input?.json);
                                                        onChange(template);
                                                        setPrefillOpen(false);
                                                    }, children: [_jsx(SquareCode, { className: "size-4" }), _jsx("span", { children: "Template" }), _jsx("span", { className: "ml-auto text-xs text-muted-foreground", children: "Empty schema structure" })] }), isAuthenticated ? (_jsxs(CommandItem, { disabled: isGeneratingSample, onSelect: () => {
                                                        handleGenerateSample();
                                                        setPrefillOpen(false);
                                                    }, children: [isGeneratingSample ? (_jsx(Loader2Icon, { className: "size-4 animate-spin" })) : (_jsx(Sparkles, { className: "size-4" })), _jsx("span", { children: "Mock Input" }), _jsx("span", { className: "ml-auto text-xs text-muted-foreground", children: "AI-generated data" })] })) : (_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsxs(CommandItem, { disabled: true, className: "opacity-50", children: [_jsx(Sparkles, { className: "size-4" }), _jsx("span", { children: "Mock Input" }), _jsx("span", { className: "ml-auto text-xs text-muted-foreground", children: "Login required" })] }) }), _jsx(TooltipContent, { children: "Login to generate a mock input using AI" })] }))] }) }) }) })] })), portals?.actionBar?.post, clearAgentState && selectedAgent && (_jsxs(Button, { "aria-label": "Clear conversation history", size: "sm", variant: "outline", className: "ml-auto font-normal bg-background dark:bg-background hover:bg-background dark:hover:bg-background dark:hover:border-border/50 text-foreground hover:text-destructive", onClick: () => clearAgentState(selectedAgent), children: [_jsx(Trash2, { className: "size-4" }), "Clear Thread"] }))] }), _jsxs(PromptInput, { onSubmit: onSubmit, children: [_jsx(PromptInputBody, { children: _jsx("div", { className: "min-h-[120px] w-full flex flex-col transition-[min-height] duration-200", children: !selectedAgent ? (_jsx("div", { className: "flex flex-col flex-1 items-center justify-center py-6 px-4 text-center", children: _jsx("p", { className: "text-sm text-muted-foreground/70", children: "Select an agent to get started." }) })) : ((() => {
                                switch (inputType) {
                                    case 'object':
                                        return (_jsx(JsonEditor, { "aria-invalid": !isValidInput, onChange: onChange, onSubmit: onSubmit, onValidationChange: setMonacoHasErrors, schema: selectedAgentData?.schema.input?.json, schemaUri: `agentuity://schema/${selectedAgentData?.metadata.id}/input`, value: value }));
                                    case 'string':
                                        return (_jsx(PromptInputTextarea, { className: "min-h-[120px]", onChange: (e) => onChange(e.target.value), placeholder: "Enter a message to send...", value: value }));
                                    default:
                                        return (_jsxs("div", { className: "flex flex-col flex-1 items-center justify-center py-8 px-4 text-center", children: [_jsx("p", { className: "text-sm text-muted-foreground", children: _jsx("span", { className: "font-medium", children: "This agent has no input schema." }) }), _jsxs(Button, { "aria-label": "Run Agent", size: "sm", variant: "default", disabled: isLoading, onClick: onSubmit, className: "mt-2", children: [isLoading ? (_jsx(Loader2Icon, { className: "size-4 animate-spin mr-2" })) : (_jsx(SendIcon, { className: "size-4 mr-2" })), "Run Agent"] })] }));
                                }
                            })()) }) }), _jsx(PromptInputFooter, { className: cn('pt-0', !selectedAgent && 'pb-0'), children: selectedAgent && inputType !== 'none' && (_jsx(Button, { "aria-label": "Submit", size: "icon", variant: "default", disabled: isSubmitDisabled, onClick: () => {
                                logger.debug('🔥 Submit button clicked! inputType:', inputType, 'value:', value);
                                onSubmit();
                            }, className: cn('ml-auto', isSubmitDisabled && 'opacity-10!'), children: isLoading ? (_jsx(Loader2Icon, { className: "size-4 animate-spin" })) : (_jsx(ArrowUp, { className: "size-4" })) })) })] })] }));
}
//# sourceMappingURL=input-section.js.map