'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import * as React from 'react';
import { Check, ChevronsUpDown } from 'lucide-react';
import { getSupportedModels } from '../../../../app/actions/get-supported-models.js';
import { updateModel } from '../../../../app/actions/update-model.js';
import { Button } from '../../../ui/button.js';
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, } from '../../../ui/command.js';
import { Popover, PopoverContent, PopoverTrigger } from '../../../ui/popover.js';
import { cn } from '../../../../lib/utils.js';
/**
 * ModelPicker
 *
 * A combobox that lets the user choose the default LLM model. On mount it
 * calls the `getSupportedModels` server action to populate suggestions for
 * the currently configured agent; the user may also type any free-text model
 * identifier. On selection the new value is persisted via `updateModel`.
 */
export function ModelPicker({ initialModel, onModelChange, disabled, className, }) {
    const [open, setOpen] = React.useState(false);
    const [models, setModels] = React.useState([]);
    const [loading, setLoading] = React.useState(true);
    const [saving, setSaving] = React.useState(false);
    const [value, setValue] = React.useState(initialModel);
    const [inputValue, setInputValue] = React.useState(initialModel);
    const [error, setError] = React.useState(null);
    // Load advertised models on mount
    React.useEffect(() => {
        getSupportedModels()
            .then(setModels)
            .finally(() => setLoading(false));
    }, []);
    // Keep local state in sync when initialModel prop changes
    React.useEffect(() => {
        setValue(initialModel);
        setInputValue(initialModel);
    }, [initialModel]);
    const filteredModels = models.filter((m) => m.toLowerCase().includes(inputValue.toLowerCase()));
    const handleSelect = async (model) => {
        setOpen(false);
        await persist(model);
    };
    const handleInputChange = (e) => {
        setInputValue(e.target.value);
        if (!open)
            setOpen(true);
    };
    const handleInputKeyDown = async (e) => {
        if (e.key === 'Enter') {
            e.preventDefault();
            setOpen(false);
            await persist(inputValue);
        }
        if (e.key === 'Escape') {
            setOpen(false);
            // Revert input to last saved value
            setInputValue(value);
        }
    };
    const persist = async (model) => {
        if (!model.trim() || model === value)
            return;
        setSaving(true);
        setError(null);
        try {
            const result = await updateModel(model);
            if (result.ok) {
                setValue(model);
                onModelChange?.(model);
            }
            else {
                setError(result.error ?? 'Failed to save model');
                setInputValue(value); // revert
            }
        }
        finally {
            setSaving(false);
        }
    };
    const isDisabled = (disabled ?? false) || loading || saving;
    return (_jsxs("div", { className: cn('flex flex-col gap-1', className), children: [_jsxs(Popover, { open: open, onOpenChange: setOpen, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsxs(Button, { variant: "outline", role: "combobox", "aria-expanded": open, disabled: isDisabled, className: "w-full justify-between font-normal", children: [_jsx("span", { className: "truncate", children: loading ? 'Loading models…' : saving ? 'Saving…' : (value ?? 'Select model…') }), _jsx(ChevronsUpDown, { className: "ms-2 h-4 w-4 shrink-0 opacity-50" })] }) }), _jsx(PopoverContent, { className: "w-[var(--radix-popover-trigger-width)] p-0", align: "start", children: _jsxs(Command, { children: [_jsx(CommandInput, { placeholder: "Search or type a model ID\u2026", value: inputValue, onChange: handleInputChange, onKeyDown: handleInputKeyDown }), _jsxs(CommandList, { children: [!loading && filteredModels.length === 0 && (_jsx(CommandEmpty, { children: models.length === 0
                                                ? 'No models advertised for this agent.'
                                                : 'No match — press Enter to use this value.' })), filteredModels.length > 0 && (_jsx(CommandGroup, { children: filteredModels.map((model) => (_jsxs(CommandItem, { selected: model === value, onClick: () => handleSelect(model), children: [_jsx(Check, { className: cn('me-2 h-4 w-4', model === value ? 'opacity-100' : 'opacity-0') }), model] }, model))) }))] })] }) })] }), Boolean(error) && _jsx("p", { className: "text-destructive text-sm", children: error })] }));
}
