import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useCallback, useState, useEffect, useRef } from "react";
import { Select } from "../../../components/ui/select";
import { setupWizardService, } from "../../../setup/services/setupWizardService";
import { AlertCircle, RefreshCw, Search, Settings, Plus } from "lucide-react";
import { Button } from "../../../components/ui/button";
import { Card } from "../../../components/ui/card";
import { SettingsPanelLayout } from "../SettingsPanelLayout";
import { Splitter } from "../../ui/Splitter";
import { ItemConfigPanel } from "./ItemConfigPanel";
import { useEditContext } from "../../client/editContext";
/**
 * Settings panel for Search configuration.
 * Configure search index and embeddings models.
 */
export function SearchConfigPanel() {
    const [state, setState] = useState("loading");
    const [embeddingsModels, setEmbeddingsModels] = useState([]);
    const [validationModels, setValidationModels] = useState([]);
    const [searchSettingsExists, setSearchSettingsExists] = useState(false);
    const [searchSettingsItemId, setSearchSettingsItemId] = useState(null);
    const [error, setError] = useState(null);
    const [selectedModelId, setSelectedModelId] = useState("");
    const [selectedValidationModelId, setSelectedValidationModelId] = useState("");
    const [saving, setSaving] = useState(false);
    const [savingValidation, setSavingValidation] = useState(false);
    const [creating, setCreating] = useState(false);
    const previousModelId = useRef("");
    const previousValidationModelId = useRef("");
    const hasLoaded = useRef(false);
    const editContext = useEditContext();
    // Sidebar editor state
    const [showEditor, setShowEditor] = useState(false);
    const loadData = useCallback(async () => {
        try {
            setState("loading");
            setError(null);
            // Load search settings info, models, and current config in parallel
            const [settingsInfo, models, chatModels, config, validationConfig] = await Promise.all([
                setupWizardService.getSearchSettingsInfo(),
                setupWizardService.getEmbeddingsModels(),
                setupWizardService.getChatModels(),
                setupWizardService.getEmbeddingsConfig(),
                setupWizardService.getValidationConfig(),
            ]);
            setSearchSettingsExists(settingsInfo.exists);
            setSearchSettingsItemId(settingsInfo.itemId || null);
            setEmbeddingsModels(models);
            setValidationModels(chatModels);
            // Pre-select the currently configured model
            if (config.modelId) {
                // Normalize GUID format: remove braces and convert to lowercase for comparison
                const normalizeGuid = (guid) => guid.replace(/[{}]/g, "").toLowerCase();
                const normalizedConfigId = normalizeGuid(config.modelId);
                const foundModel = models.find((m) => normalizeGuid(m.id) === normalizedConfigId);
                // Use the original model ID from the models array (not the config ID) to ensure consistency
                if (foundModel) {
                    setSelectedModelId(foundModel.id);
                    previousModelId.current = foundModel.id;
                }
                else {
                    // Fallback: use normalized config ID if model not found
                    setSelectedModelId(normalizedConfigId);
                    previousModelId.current = normalizedConfigId;
                }
            }
            else {
                setSelectedModelId("");
                previousModelId.current = "";
            }
            if (validationConfig.modelId) {
                const normalizeGuid = (guid) => guid.replace(/[{}]/g, "").toLowerCase();
                const normalizedConfigId = normalizeGuid(validationConfig.modelId);
                const foundModel = chatModels.find((m) => normalizeGuid(m.id) === normalizedConfigId);
                if (foundModel) {
                    setSelectedValidationModelId(foundModel.id);
                    previousValidationModelId.current = foundModel.id;
                }
                else {
                    setSelectedValidationModelId(normalizedConfigId);
                    previousValidationModelId.current = normalizedConfigId;
                }
            }
            else {
                setSelectedValidationModelId("");
                previousValidationModelId.current = "";
            }
            setState("success");
            hasLoaded.current = true;
        }
        catch (e) {
            setState("error");
            setError(e?.message || "Failed to load search configuration");
            hasLoaded.current = true;
        }
    }, []);
    const handleCreate = useCallback(async () => {
        try {
            setCreating(true);
            setError(null);
            const itemId = await setupWizardService.createSearchSettingsItem();
            setSearchSettingsExists(true);
            setSearchSettingsItemId(itemId);
            // Reload to get the full state
            await loadData();
        }
        catch (e) {
            setError(e?.message || "Failed to create search settings item");
        }
        finally {
            setCreating(false);
        }
    }, [loadData]);
    const handleSave = useCallback(async (modelId) => {
        if (!modelId) {
            return;
        }
        const selectedModel = embeddingsModels.find((m) => m.id === modelId);
        if (!selectedModel) {
            return;
        }
        try {
            setSaving(true);
            setError(null);
            await setupWizardService.setEmbeddingsConfig({
                modelId: modelId,
                providerId: selectedModel.providerId,
            });
            setState("success");
        }
        catch (e) {
            setState("error");
            setError(e?.message || "Failed to save embeddings configuration");
        }
        finally {
            setSaving(false);
        }
    }, [embeddingsModels]);
    const handleSaveValidation = useCallback(async (modelId) => {
        try {
            setSavingValidation(true);
            setError(null);
            await setupWizardService.setValidationConfig({
                modelId: modelId || undefined,
            });
            setState("success");
        }
        catch (e) {
            setState("error");
            setError(e?.message || "Failed to save validation configuration");
        }
        finally {
            setSavingValidation(false);
        }
    }, []);
    useEffect(() => {
        loadData();
    }, [loadData]);
    // Auto-save when model is selected (but not on initial load)
    useEffect(() => {
        if (hasLoaded.current &&
            selectedModelId !== previousModelId.current &&
            embeddingsModels.length > 0 &&
            state === "success" &&
            searchSettingsExists) {
            previousModelId.current = selectedModelId;
            // Only save if a model is actually selected (not empty)
            if (selectedModelId) {
                handleSave(selectedModelId);
            }
        }
    }, [
        selectedModelId,
        embeddingsModels,
        state,
        handleSave,
        searchSettingsExists,
    ]);
    useEffect(() => {
        if (hasLoaded.current &&
            selectedValidationModelId !== previousValidationModelId.current &&
            state === "success" &&
            searchSettingsExists) {
            previousValidationModelId.current = selectedValidationModelId;
            handleSaveValidation(selectedValidationModelId);
        }
    }, [
        selectedValidationModelId,
        state,
        handleSaveValidation,
        searchSettingsExists,
    ]);
    const handleToggleEditor = () => {
        setShowEditor(!showEditor);
        if (showEditor) {
            loadData();
        }
    };
    // Build the main content
    const mainContent = (_jsxs(SettingsPanelLayout, { children: [state === "loading" && (_jsx("div", { className: "flex items-center justify-center py-8", children: _jsxs("div", { className: "text-neutral-grey-50 flex items-center gap-2 text-sm", children: [_jsx(RefreshCw, { className: "h-4 w-4 animate-spin" }), "Loading..."] }) })), state !== "loading" && !searchSettingsExists && (_jsx(Card, { icon: _jsx(Settings, { strokeWidth: 1, className: "h-5 w-5" }), title: "Search settings", description: "Create the search settings item to configure embeddings model, validation model, and dimensions.", children: _jsxs("div", { className: "space-y-4", children: [_jsx("p", { className: "text-neutral-grey-50 text-sm", children: "The Search Settings item contains configuration for the search index, including the embeddings model, validation model, and vector dimensions." }), _jsx(Button, { onClick: handleCreate, disabled: creating, className: "w-full", children: creating ? (_jsxs(_Fragment, { children: [_jsx(RefreshCw, { strokeWidth: 1, className: "mr-2 h-4 w-4 animate-spin" }), "Creating..."] })) : (_jsxs(_Fragment, { children: [_jsx(Plus, { strokeWidth: 1, className: "mr-2 h-4 w-4" }), "Create search settings"] })) }), error && (_jsx("div", { className: "border-feedback-red bg-feedback-red-light text-feedback-red rounded border p-2 text-xs whitespace-pre-wrap", children: error }))] }) })), state !== "loading" && searchSettingsExists && (_jsx(Card, { icon: _jsx(Search, { strokeWidth: 1, className: "h-5 w-5" }), title: "Search models", description: "Select the embeddings and validation models used to build and query the search index.", children: _jsxs("div", { className: "space-y-4", children: [embeddingsModels.length === 0 && (_jsx("div", { className: "border-feedback-orange bg-feedback-orange-light rounded border p-4", children: _jsxs("div", { className: "flex items-start gap-3", children: [_jsx(AlertCircle, { className: "text-feedback-orange mt-0.5 h-5 w-5 shrink-0" }), _jsxs("div", { className: "flex-1", children: [_jsx("p", { className: "text-feedback-orange mb-1 text-sm font-medium", children: "No embeddings models found" }), _jsx("p", { className: "text-feedback-orange mb-3 text-xs", children: "Please install embeddings models in the model settings page." })] })] }) })), embeddingsModels.length > 0 && (_jsxs("div", { className: "space-y-2", children: [_jsx("label", { htmlFor: "embeddings-model", className: "text-neutral-grey-100 mb-1 block text-sm font-medium", children: "Embeddings model" }), _jsx(Select, { id: "embeddings-model", "data-testid": "search-config-embeddings-model-select", value: selectedModelId, onValueChange: setSelectedModelId, options: embeddingsModels.map((model) => ({
                                        value: model.id,
                                        label: `${model.name}${model.providerName ? ` (${model.providerName})` : ""}`,
                                    })), placeholder: "Select...", disabled: saving }), saving && (_jsxs("div", { className: "text-neutral-grey-50 flex items-center gap-2 text-xs", children: [_jsx(RefreshCw, { className: "h-3 w-3 animate-spin" }), "Saving..."] }))] })), validationModels.length > 0 && (_jsxs("div", { className: "space-y-2", children: [_jsx("label", { htmlFor: "validation-model", className: "text-neutral-grey-100 mb-1 block text-sm font-medium", children: "Validation model" }), _jsx(Select, { id: "validation-model", "data-testid": "search-config-validation-model-select", value: selectedValidationModelId, onValueChange: setSelectedValidationModelId, options: [
                                        { value: "", label: "None" },
                                        ...validationModels.map((model) => ({
                                            value: model.id,
                                            label: `${model.name}${model.providerName ? ` (${model.providerName})` : ""}`,
                                        })),
                                    ], placeholder: "Select...", disabled: savingValidation }), savingValidation && (_jsxs("div", { className: "text-neutral-grey-50 flex items-center gap-2 text-xs", children: [_jsx(RefreshCw, { className: "h-3 w-3 animate-spin" }), "Saving..."] }))] })), searchSettingsItemId && (_jsx("div", { className: "flex justify-end", children: _jsxs(Button, { size: "sm", variant: showEditor ? "default" : "outline", onClick: handleToggleEditor, className: "shrink-0", children: [_jsx(Settings, { className: "h-4 w-4", strokeWidth: 1.5 }), "Edit advanced settings"] }) })), error && (_jsx("div", { className: "border-feedback-red bg-feedback-red-light text-feedback-red rounded border p-2 text-xs whitespace-pre-wrap", children: error }))] }) }))] }));
    // Build splitter panels - only show config panel when editor is open
    const panels = showEditor && searchSettingsItemId
        ? [
            {
                name: "search-config",
                defaultSize: "auto",
                content: mainContent,
                className: "overflow-hidden",
            },
            {
                name: "search-settings-editor",
                defaultSize: 400,
                content: (_jsx(ItemConfigPanel, { itemId: searchSettingsItemId, title: "Search Settings", onClose: handleToggleEditor }, searchSettingsItemId)),
                className: "overflow-hidden",
            },
        ]
        : [
            {
                name: "search-config",
                defaultSize: "auto",
                content: mainContent,
                className: "overflow-hidden",
            },
        ];
    return (_jsx(Splitter, { panels: panels, localStorageKey: "search-config-panel-splitter", direction: editContext?.isMobile ? "vertical" : "horizontal", className: "h-full" }));
}
export default SearchConfigPanel;
//# sourceMappingURL=SearchConfigPanel.js.map