import React from 'react';
import { SETTING_CONFIGS } from '../components/ModelControls';
export const useModelSettingsEditor = ({ defaultModel, updateModel }) => {
    const [settingEditor, setSettingEditor] = React.useState(null);
    const [settingInputValue, setSettingInputValue] = React.useState('');
    const [settingError, setSettingError] = React.useState(null);
    const openSettingEditor = React.useCallback((key, currentValue) => {
        if (!defaultModel)
            return;
        const config = SETTING_CONFIGS[key];
        const settings = (defaultModel.settings ?? {});
        const extractStoredValue = () => {
            if (config.type === 'number') {
                const raw = settings[key];
                return typeof raw === 'number' ? raw : undefined;
            }
            if (key === 'reasoningEffort') {
                if (typeof settings.reasoningEffort === 'string')
                    return settings.reasoningEffort;
                const reasoning = settings.reasoning;
                if (typeof reasoning?.effort === 'string')
                    return reasoning.effort;
                return undefined;
            }
            if (key === 'textVerbosity') {
                if (typeof settings.textVerbosity === 'string')
                    return settings.textVerbosity;
                const text = settings.text;
                if (typeof text?.verbosity === 'string')
                    return text.verbosity;
                return undefined;
            }
            const raw = settings[key];
            return typeof raw === 'string' || typeof raw === 'number' ? raw : undefined;
        };
        const storedValue = extractStoredValue();
        const fallback = config.fallback;
        const initialValue = currentValue ?? storedValue ?? fallback;
        setSettingEditor({ key, value: initialValue });
        setSettingInputValue(String(initialValue));
        setSettingError(null);
    }, [defaultModel]);
    const closeSettingEditor = React.useCallback(() => {
        setSettingEditor(null);
        setSettingInputValue('');
        setSettingError(null);
    }, []);
    const handleSettingInputChange = React.useCallback((value) => {
        setSettingInputValue(value);
        setSettingError(null);
    }, []);
    const handleSettingSubmit = React.useCallback(async (event) => {
        event.preventDefault();
        if (!settingEditor || !defaultModel)
            return;
        const config = SETTING_CONFIGS[settingEditor.key];
        const existingSettings = (defaultModel.settings ?? {});
        const nextSettings = { ...existingSettings };
        if (config.type === 'number') {
            const numericValue = Number(settingInputValue);
            if (Number.isNaN(numericValue)) {
                setSettingError('Please enter a valid number.');
                return;
            }
            const clampedValue = Math.min(config.max, Math.max(config.min, numericValue));
            const formattedValue = config.step === 1
                ? Math.round(clampedValue)
                : Number(clampedValue.toFixed(2));
            nextSettings[settingEditor.key] = formattedValue;
        }
        else {
            const normalizedValue = settingInputValue.trim().toLowerCase();
            if (!normalizedValue) {
                setSettingError('Please choose a value.');
                return;
            }
            const isValid = config.options.some((option) => option.value === normalizedValue);
            if (!isValid) {
                setSettingError('Please choose one of the available options.');
                return;
            }
            if (settingEditor.key === 'reasoningEffort') {
                const existingReasoning = existingSettings.reasoning;
                nextSettings.reasoningEffort = normalizedValue;
                nextSettings.reasoning = {
                    ...(existingReasoning && typeof existingReasoning === 'object' ? existingReasoning : {}),
                    effort: normalizedValue
                };
            }
            else if (settingEditor.key === 'textVerbosity') {
                const existingText = existingSettings.text;
                nextSettings.textVerbosity = normalizedValue;
                nextSettings.text = {
                    ...(existingText && typeof existingText === 'object' ? existingText : {}),
                    verbosity: normalizedValue
                };
            }
            else {
                nextSettings[settingEditor.key] = normalizedValue;
            }
        }
        updateModel(defaultModel.id, {
            settings: nextSettings
        });
        closeSettingEditor();
    }, [defaultModel, settingEditor, settingInputValue, updateModel, closeSettingEditor]);
    return {
        settingEditor,
        settingInputValue,
        settingError,
        openSettingEditor,
        closeSettingEditor,
        handleSettingInputChange,
        handleSettingSubmit
    };
};
