import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React from 'react';
import { useModelContext } from '../contexts/ModelContext';
import { ModelManagerInner } from './ModelManager';
import { useTheme } from '../theme';
import { useCredentialSync } from '../contexts/CredentialContext';
import { getDefaultModelTemplate, listModelProviderDefinitions } from '../config/modelProviders';
export const ModelSettingsSection = () => {
    const { models, defaultModel, addModel, setDefaultModel } = useModelContext();
    const [isMenuOpen, setIsMenuOpen] = React.useState(false);
    const menuRef = React.useRef(null);
    const theme = useTheme();
    const { isLoadingInitialCredentials } = useCredentialSync();
    const [availableProviders, setAvailableProviders] = React.useState(() => listModelProviderDefinitions());
    const templateByProvider = React.useMemo(() => {
        const entries = availableProviders
            .map((definition) => {
            const template = getDefaultModelTemplate(definition.id);
            return template ? [definition.id, template] : null;
        })
            .filter(Boolean);
        return new Map(entries);
    }, [availableProviders]);
    const providersWithTemplates = React.useMemo(() => {
        return availableProviders.filter((definition) => templateByProvider.has(definition.id));
    }, [availableProviders, templateByProvider]);
    const cloneTemplate = React.useCallback((template) => ({
        ...template,
        connection: template.connection ? { ...template.connection } : undefined,
        settings: template.settings ? { ...template.settings } : undefined
    }), []);
    React.useEffect(() => {
        if (!isMenuOpen)
            return;
        const handleClickOutside = (event) => {
            if (!menuRef.current?.contains(event.target)) {
                setIsMenuOpen(false);
            }
        };
        const handleKeyDown = (event) => {
            if (event.key === 'Escape') {
                setIsMenuOpen(false);
            }
        };
        document.addEventListener('mousedown', handleClickOutside);
        document.addEventListener('keydown', handleKeyDown);
        setAvailableProviders(listModelProviderDefinitions());
        return () => {
            document.removeEventListener('mousedown', handleClickOutside);
            document.removeEventListener('keydown', handleKeyDown);
        };
    }, [isMenuOpen]);
    const handleAddModel = React.useCallback((provider) => {
        if (isLoadingInitialCredentials) {
            return;
        }
        const template = templateByProvider.get(provider);
        if (!template)
            return;
        const newModelId = addModel(cloneTemplate(template));
        setDefaultModel(newModelId);
        setIsMenuOpen(false);
    }, [addModel, cloneTemplate, setDefaultModel, templateByProvider, isLoadingInitialCredentials]);
    const topModels = models.slice(0, 3);
    return (_jsxs("div", { className: theme.modelSettings.container, children: [_jsxs("div", { className: theme.modelSettings.header, children: [_jsxs("div", { children: [_jsx("h2", { className: theme.modelSettings.heading, children: "Language Models" }), _jsx("p", { className: theme.modelSettings.description, children: "Manage the language models available in your playground." })] }), _jsxs("div", { className: 'flex items-center gap-3', children: [_jsxs("span", { className: theme.modelSettings.countBadge, children: [models.length, " ", models.length === 1 ? 'model' : 'models'] }), _jsxs("div", { className: 'relative inline-flex text-left', ref: menuRef, children: [_jsxs("button", { type: 'button', onClick: () => setIsMenuOpen((open) => !open), className: theme.buttons.primary, "aria-haspopup": 'menu', "aria-expanded": isMenuOpen, disabled: isLoadingInitialCredentials, children: ["Add model", _jsx("svg", { className: 'ml-2 h-4 w-4', xmlns: 'http://www.w3.org/2000/svg', viewBox: '0 0 20 20', fill: 'currentColor', "aria-hidden": 'true', children: _jsx("path", { d: 'M5.23 7.21a.75.75 0 011.06.02L10 11.173l3.71-3.943a.75.75 0 111.1 1.02l-4.25 4.5a.75.75 0 01-1.1 0l-4.25-4.5a.75.75 0 01.02-1.06z' }) })] }), isMenuOpen && (_jsxs("div", { className: theme.modelSettings.menu, role: 'menu', "aria-orientation": 'vertical', children: [providersWithTemplates.map((definition) => {
                                                const template = templateByProvider.get(definition.id);
                                                const summary = template?.model ?? '';
                                                return (_jsxs("button", { type: 'button', onClick: () => handleAddModel(definition.id), className: theme.modelSettings.menuItem, role: 'menuitem', children: [_jsx("span", { children: definition.displayName }), summary && (_jsx("span", { className: theme.modelSettings.summaryItemMuted, children: summary }))] }, definition.id));
                                            }), providersWithTemplates.length === 0 && (_jsx("div", { className: 'px-4 py-2 text-sm text-neutral-500', role: 'none', children: "No providers available. Install a provider plugin to add models." }))] }))] })] })] }), _jsxs("div", { className: 'space-y-4', children: [_jsxs("div", { className: theme.modelSettings.summary, children: [_jsxs("p", { children: [_jsx("span", { className: theme.modelSettings.summaryItem, children: "Default model:" }), ' ', defaultModel ? defaultModel.label : 'None selected'] }), topModels.length > 0 && (_jsxs("ul", { className: theme.modelSettings.summaryList, children: [topModels.map((model) => (_jsxs("li", { children: [_jsx("span", { className: theme.modelSettings.summaryItem, children: model.label }), _jsxs("span", { className: theme.modelSettings.summaryItemMuted, children: [" \u00B7 ", model.provider, " \u00B7 ", model.model] })] }, model.id))), models.length > topModels.length && (_jsxs("li", { className: `${theme.modelSettings.summaryItemMuted} italic`, children: [models.length - topModels.length, " more ", models.length - topModels.length === 1 ? 'model' : 'models'] }))] })), topModels.length === 0 && (_jsx("p", { className: theme.modelSettings.summaryEmpty, children: "No models configured yet." }))] }), _jsx("div", { className: theme.modelSettings.managerSection, children: _jsx(ModelManagerInner, {}) })] })] }));
};
