import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, useEffect, useMemo, useRef, useCallback } from "react";
import { Button } from "../../../components/ui/button";
import { Input } from "../../../components/ui/input";
import { Select } from "../../../components/ui/select";
import { Dialog, DialogContent, DialogFooter, } from "../../../components/ui/dialog";
import { StyledDialogTitle } from "../../../components/ui/styled-dialog-title";
import { setupWizardService, } from "../../../setup/services/setupWizardService";
import { CheckCircle, Plus, RefreshCw, Settings, Trash2 } from "lucide-react";
import { useEditContext } from "../../client/editContext";
import { useSearchParams } from "../../client/navigation";
import { Splitter } from "../../ui/Splitter";
import { ProviderConfigPanel } from "./ProviderConfigPanel";
const SELECTED_PROVIDER_QUERY_PARAM = "providerId";
/**
 * Settings panel for AI Providers configuration.
 * Configure AI providers (Anthropic, OpenAI, OpenRouter, Google Vertex AI).
 */
export function ProvidersPanel() {
    const editContext = useEditContext();
    const searchParams = useSearchParams();
    const [state, setState] = useState("loading");
    const [providers, setProviders] = useState([]);
    const [providerTypes, setProviderTypes] = useState([]);
    const [error, setError] = useState(null);
    const [showForm, setShowForm] = useState(false);
    const [creating, setCreating] = useState(false);
    const [deleting, setDeleting] = useState(null);
    const [formData, setFormData] = useState({
        type: "",
        name: "",
        apiKey: "",
        connectionString: "",
        baseUrl: "",
    });
    const prevShowFormRef = useRef(false);
    // URL-synced provider selection
    const [urlSelectedProviderId, setUrlSelectedProviderId] = useState(searchParams.get(SELECTED_PROVIDER_QUERY_PARAM) ||
        (typeof window !== "undefined"
            ? new URLSearchParams(window.location.search).get(SELECTED_PROVIDER_QUERY_PARAM)
            : null));
    const [selectedProvider, setSelectedProvider] = useState(null);
    const createEmptyFormData = useCallback(() => ({
        type: "",
        name: "",
        apiKey: "",
        connectionString: "",
        baseUrl: "",
    }), []);
    useEffect(() => {
        const key = searchParams.get(SELECTED_PROVIDER_QUERY_PARAM) ||
            (typeof window !== "undefined"
                ? new URLSearchParams(window.location.search).get(SELECTED_PROVIDER_QUERY_PARAM)
                : null);
        setUrlSelectedProviderId(key);
    }, [searchParams]);
    useEffect(() => {
        if (typeof window === "undefined")
            return;
        const handlePopState = () => {
            setUrlSelectedProviderId(new URLSearchParams(window.location.search).get(SELECTED_PROVIDER_QUERY_PARAM));
        };
        window.addEventListener("popstate", handlePopState);
        return () => window.removeEventListener("popstate", handlePopState);
    }, []);
    useEffect(() => {
        if (!urlSelectedProviderId) {
            if (selectedProvider)
                setSelectedProvider(null);
            return;
        }
        const match = providers.find((p) => p.id === urlSelectedProviderId);
        if (match && selectedProvider?.id !== match.id) {
            setSelectedProvider(match);
        }
    }, [providers, urlSelectedProviderId, selectedProvider]);
    const updateSelectedProviderUrl = useCallback((providerId) => {
        editContext?.updateUrl({
            [SELECTED_PROVIDER_QUERY_PARAM]: providerId || undefined,
        });
        setUrlSelectedProviderId(providerId || null);
    }, [editContext]);
    const handleOpenConfig = (provider) => {
        setSelectedProvider(provider);
        updateSelectedProviderUrl(provider.id);
    };
    const handleCloseConfig = () => {
        setSelectedProvider(null);
        updateSelectedProviderUrl(null);
    };
    // Get the selected provider type's default base URL
    const selectedProviderType = useMemo(() => providerTypes.find((p) => p.providerId === formData.type), [providerTypes, formData.type]);
    const loadData = async () => {
        try {
            setState("loading");
            setError(null);
            const [providersData, providerTypesData] = await Promise.all([
                setupWizardService.getProviders(),
                setupWizardService.getProviderTypes(),
            ]);
            setProviders(providersData);
            setProviderTypes(providerTypesData);
            setState("success");
        }
        catch (e) {
            setState("error");
            setError(e?.message || "Failed to load data");
        }
    };
    const handleCreate = async () => {
        if (!formData.type ||
            !formData.name ||
            (!formData.apiKey && !formData.connectionString)) {
            setError("Provider type, name, and at least one secret source are required");
            return;
        }
        try {
            setCreating(true);
            setError(null);
            const baseUrl = formData.baseUrl || selectedProviderType?.defaultBaseUrl || "";
            await setupWizardService.createProvider({
                ...formData,
                baseUrl,
            });
            setFormData(createEmptyFormData());
            setShowForm(false);
            await loadData();
        }
        catch (e) {
            setError(e?.message || "Failed to create provider");
        }
        finally {
            setCreating(false);
        }
    };
    // Reset form when dialog opens (only when transitioning from closed to open)
    useEffect(() => {
        const wasClosed = !prevShowFormRef.current;
        const isOpen = showForm;
        if (isOpen && wasClosed) {
            setFormData(createEmptyFormData());
            setError(null);
        }
        prevShowFormRef.current = showForm;
    }, [createEmptyFormData, showForm]);
    const handleDelete = (providerId) => {
        editContext?.confirm({
            header: "Delete Provider",
            message: "Are you sure you want to delete this provider?",
            acceptLabel: "Delete",
            showCancel: true,
            accept: async () => {
                try {
                    setDeleting(providerId);
                    setError(null);
                    await setupWizardService.deleteProvider(providerId);
                    await loadData();
                }
                catch (e) {
                    setError(e?.message || "Failed to delete provider");
                }
                finally {
                    setDeleting(null);
                }
            },
        });
    };
    useEffect(() => {
        loadData();
    }, []);
    // Build provider type options
    const providerTypeOptions = useMemo(() => providerTypes.map((p) => ({
        value: p.providerId,
        label: p.displayName,
    })), [providerTypes]);
    // Build the providers list content
    const providersListContent = (_jsx("div", { className: "h-full overflow-auto p-4", children: _jsx("div", { className: "mx-auto", children: _jsx("div", { className: "rounded-lg bg-white p-4", children: _jsxs("div", { className: "space-y-4", children: [providerTypes.length === 0 && state === "success" && (_jsx("div", { className: "rounded border border-yellow-200 bg-yellow-50 p-3 text-sm text-yellow-800", children: "No provider types are available. Please check the server configuration." })), _jsx(Dialog, { open: showForm, onOpenChange: (open) => {
                                setShowForm(open);
                                if (open) {
                                    setFormData(createEmptyFormData());
                                    setError(null);
                                }
                            }, children: _jsxs(DialogContent, { className: "max-w-xl", children: [_jsx(StyledDialogTitle, { icon: _jsx(Plus, { strokeWidth: 1 }), title: "Add Provider" }), _jsxs("div", { className: "flex flex-col gap-6 p-8", children: [_jsxs("div", { children: [_jsx("label", { htmlFor: "provider-type", className: "mb-1 block text-sm font-medium text-gray-700", children: "Provider Type" }), _jsx(Select, { id: "provider-type", value: formData.type, onValueChange: (value) => {
                                                            const providerType = providerTypes.find((p) => p.providerId === value);
                                                            setFormData((prev) => ({
                                                                ...prev,
                                                                type: value,
                                                                name: prev.name || providerType?.displayName || value,
                                                            }));
                                                        }, options: providerTypeOptions, placeholder: "Select provider type" })] }), _jsxs("div", { children: [_jsx("label", { htmlFor: "provider-name", className: "mb-1 block text-sm font-medium text-gray-700", children: "Name" }), _jsx(Input, { id: "provider-name", value: formData.name, onChange: (e) => setFormData({ ...formData, name: e.target.value }), placeholder: "My Provider" })] }), _jsxs("div", { children: [_jsx("label", { htmlFor: "provider-secret-input", className: "mb-1 block text-sm font-medium text-gray-700", children: "API Key (optional)" }), _jsx(Input, { id: "provider-secret-input", type: "password", name: "ai-provider-api-key", autoComplete: "new-password", autoCapitalize: "none", spellCheck: false, value: formData.apiKey || "", onChange: (e) => setFormData({ ...formData, apiKey: e.target.value }), placeholder: "sk-..." })] }), _jsxs("div", { children: [_jsx("label", { htmlFor: "provider-connection-string-input", className: "mb-1 block text-sm font-medium text-gray-700", children: "Connection String Name (optional)" }), _jsx(Input, { id: "provider-connection-string-input", type: "text", value: formData.connectionString || "", onChange: (e) => setFormData({
                                                            ...formData,
                                                            connectionString: e.target.value,
                                                        }), placeholder: "parhelia.ai.provider.<providerId>" }), _jsx("p", { className: "mt-1 text-xs text-gray-500", children: "Provide at least one secret source. Runtime resolution is Sitecore first, then ConnectionStrings.config." })] }), _jsxs("div", { children: [_jsx("label", { htmlFor: "provider-baseurl", className: "mb-1 block text-sm font-medium text-gray-700", children: "Base URL (optional)" }), _jsx(Input, { id: "provider-baseurl", value: formData.baseUrl, onChange: (e) => setFormData({ ...formData, baseUrl: e.target.value }), placeholder: selectedProviderType?.defaultBaseUrl || "" })] }), error && (_jsx("div", { className: "rounded border border-red-200 bg-red-50 p-3 text-sm text-red-700", children: error }))] }), _jsxs(DialogFooter, { className: "px-6 pb-6", children: [_jsx(Button, { variant: "outline", onClick: () => {
                                                    setShowForm(false);
                                                    setFormData(createEmptyFormData());
                                                    setError(null);
                                                }, children: "Cancel" }), _jsx(Button, { onClick: handleCreate, disabled: creating ||
                                                    !formData.name ||
                                                    (!formData.apiKey && !formData.connectionString) ||
                                                    !formData.type, children: creating ? (_jsxs(_Fragment, { children: [_jsx(RefreshCw, { strokeWidth: 1, className: "mr-2 h-4 w-4 animate-spin" }), "Creating..."] })) : (_jsxs(_Fragment, { children: [_jsx(CheckCircle, { strokeWidth: 1, className: "mr-2 h-4 w-4" }), "Create"] })) })] })] }) }), providers.length > 0 && (_jsx("div", { className: "space-y-2", children: providers.map((provider) => {
                                // Look up display name from provider types
                                const providerType = providerTypes.find((p) => p.providerId === provider.type);
                                const providerTypeDisplayName = providerType?.displayName || provider.type || "Unknown";
                                const isSelected = selectedProvider?.id === provider.id;
                                return (_jsxs("div", { className: `flex flex-wrap items-center gap-2 rounded border p-3 text-sm transition-shadow hover:shadow-sm ${isSelected
                                        ? "border-blue-400 bg-blue-50"
                                        : "border-gray-200 bg-white"}`, children: [_jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("div", { className: "truncate font-medium", children: provider.name }), _jsx("div", { className: "text-xs text-gray-500", children: providerTypeDisplayName }), _jsx("div", { className: "truncate text-xs text-gray-400", children: provider.baseUrl })] }), _jsxs("div", { className: "flex shrink-0 items-center gap-2", children: [_jsxs(Button, { size: "sm", variant: isSelected ? "default" : "ghost", onClick: () => handleOpenConfig(provider), className: "shrink-0", title: "Configure provider", children: [_jsx(Settings, { className: "h-4 w-4", strokeWidth: 1.5 }), _jsx("span", { className: "hidden sm:inline", children: "Configure" })] }), _jsx("button", { onClick: () => handleDelete(provider.id), disabled: deleting === provider.id, className: "text-gray-500 hover:text-red-600 disabled:cursor-not-allowed disabled:opacity-50", title: "Delete provider", children: deleting === provider.id ? (_jsx(RefreshCw, { className: "h-4 w-4 animate-spin", strokeWidth: 1 })) : (_jsx(Trash2, { className: "h-4 w-4", strokeWidth: 1 })) })] })] }, provider.id));
                            }) })), _jsx("div", { children: _jsxs(Button, { size: "sm", onClick: () => {
                                    setFormData(createEmptyFormData());
                                    setError(null);
                                    setShowForm(true);
                                }, disabled: providerTypes.length === 0, children: [_jsx(Plus, { strokeWidth: 1, className: "h-4 w-4" }), "Add Provider"] }) }), error && !showForm && (_jsx("div", { className: "rounded border border-red-200 bg-red-50 p-2 text-xs whitespace-pre-wrap text-red-700", children: error }))] }) }) }) }));
    // Build splitter panels - only show config panel when a provider is selected
    const panels = selectedProvider?.id
        ? [
            {
                name: "providers-list",
                defaultSize: "auto",
                content: providersListContent,
                className: "overflow-hidden",
            },
            {
                name: "provider-config",
                defaultSize: 400,
                content: (_jsx(ProviderConfigPanel, { itemId: selectedProvider.id, title: `Configure: ${selectedProvider.name || "Provider"}`, onClose: handleCloseConfig }, selectedProvider.id)),
                className: "overflow-hidden",
            },
        ]
        : [
            {
                name: "providers-list",
                defaultSize: "auto",
                content: providersListContent,
                className: "overflow-hidden",
            },
        ];
    return (_jsx(Splitter, { panels: panels, localStorageKey: "providers-panel-splitter", direction: "horizontal", className: "h-full" }));
}
export default ProvidersPanel;
//# sourceMappingURL=ProvidersPanel.js.map