import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useEffect, useMemo, useCallback, useRef, } from "react";
import { Button } from "../../../components/ui/button";
import { Input } from "../../../components/ui/input";
import { Select } from "../../../components/ui/select";
import { SimpleIconButton } from "../../ui/SimpleIconButton";
import ConfirmationDialog from "../../ConfirmationDialog";
import { setupWizardService, } from "../../../setup/services/setupWizardService";
import { SetupStepError } from "../SetupStepError";
import { SetupStepBackButton, SetupStepFooter, SetupStepLayout, } from "../SetupStepLayout";
import { Server, RefreshCw, ArrowRight, Plus, ChevronDown, ChevronRight, } from "lucide-react";
import { DeleteIcon } from "../../../components/ui/delete-icon";
function normalizeProviderUrl(url) {
    return (url || "").trim().replace(/\/+$/, "").toLowerCase();
}
function getCustomProviderUrl(provider, providerTypes) {
    const baseUrl = provider.baseUrl?.trim();
    if (!baseUrl) {
        return undefined;
    }
    const normalizedBaseUrl = normalizeProviderUrl(baseUrl);
    const providerType = providerTypes.find((type) => type.providerId.toLowerCase() === provider.type.toLowerCase());
    const defaultBaseUrls = new Set(providerTypes
        .map((type) => normalizeProviderUrl(type.defaultBaseUrl))
        .filter(Boolean));
    const matchedDefaultBaseUrl = normalizeProviderUrl(providerType?.defaultBaseUrl);
    if (matchedDefaultBaseUrl) {
        defaultBaseUrls.add(matchedDefaultBaseUrl);
    }
    if (defaultBaseUrls.has(normalizedBaseUrl)) {
        return undefined;
    }
    return baseUrl;
}
export function ProviderStep({ onNext, onSkip, onBack }) {
    const confirmationDialogRef = useRef(null);
    const [loading, setLoading] = useState(true);
    const [providers, setProviders] = useState([]);
    const [providerTypes, setProviderTypes] = useState([]);
    const [error, setError] = useState(null);
    const [creating, setCreating] = useState(false);
    const [deletingId, setDeletingId] = useState(null);
    const [showAddForm, setShowAddForm] = useState(false);
    const [connectedCollapsed, setConnectedCollapsed] = useState(false);
    const [formData, setFormData] = useState({
        type: "",
        name: "",
        apiKey: "",
        connectionString: "",
        secretStorage: "sitecore",
        baseUrl: "",
    });
    const loadData = useCallback(async () => {
        try {
            const [types, existingProviders] = await Promise.all([
                setupWizardService.getProviderTypes(),
                setupWizardService.getProviders(),
            ]);
            setProviderTypes(types);
            setProviders(existingProviders);
            // If no providers exist, show the form by default
            if (existingProviders.length === 0) {
                setShowAddForm(true);
            }
        }
        catch (e) {
            setError(e?.message || "Failed to load provider data");
        }
        finally {
            setLoading(false);
        }
    }, [formData.type]);
    useEffect(() => {
        loadData();
    }, [loadData]);
    const selectedType = useMemo(() => providerTypes.find((t) => t.providerId === formData.type), [providerTypes, formData.type]);
    const handleCreate = useCallback(async () => {
        const requiresApiKey = formData.secretStorage === "sitecore";
        const requiresConnectionString = formData.secretStorage === "connectionStrings";
        if (!formData.name ||
            !formData.type ||
            (requiresApiKey && !formData.apiKey) ||
            (requiresConnectionString && !formData.connectionString)) {
            setError("Please fill in all required fields");
            return;
        }
        try {
            setCreating(true);
            setError(null);
            const providerId = await setupWizardService.createProvider({
                type: formData.type,
                name: formData.name,
                apiKey: formData.secretStorage === "sitecore" ? formData.apiKey : "",
                connectionString: formData.secretStorage === "connectionStrings"
                    ? formData.connectionString
                    : "",
                baseUrl: formData.baseUrl || selectedType?.defaultBaseUrl || "",
            });
            onNext(providerId);
        }
        catch (e) {
            setError(e?.message || "Failed to create provider");
        }
        finally {
            setCreating(false);
        }
    }, [formData, selectedType, onNext]);
    const handleDelete = useCallback((provider) => {
        const deleteProvider = async () => {
            try {
                setDeletingId(provider.id);
                await setupWizardService.deleteProvider(provider.id);
                await loadData();
            }
            catch (e) {
                setError(e?.message || "Failed to delete provider");
            }
            finally {
                setDeletingId(null);
            }
        };
        confirmationDialogRef.current?.confirm({
            header: "Remove Provider",
            message: `Remove "${provider.name}" from your connected providers?`,
            acceptLabel: "Remove",
            showCancel: true,
            accept: deleteProvider,
        });
    }, [loadData]);
    const handleNextWithExisting = () => {
        if (providers.length > 0) {
            onNext(providers[0].id);
        }
        else {
            onSkip();
        }
    };
    if (loading) {
        return (_jsxs("div", { className: "flex flex-col items-center justify-center p-12", children: [_jsx(RefreshCw, { strokeWidth: 1, className: "text-feedback-blue mb-4 h-8 w-8 animate-spin" }), _jsx("p", { className: "text-neutral-grey-50", children: "Loading AI providers..." })] }));
    }
    const addProviderButton = !showAddForm ? (_jsx("div", { className: "flex shrink-0 justify-center py-3", children: _jsxs(Button, { variant: "outline", className: "shadow-none hover:shadow-none", onClick: () => {
                setConnectedCollapsed(true);
                setShowAddForm(true);
            }, children: [_jsx(Plus, { className: "h-4 w-4", strokeWidth: 1 }), _jsx("span", { className: "text-sm font-medium", children: "Add another provider" })] }) })) : undefined;
    const footer = (_jsxs(SetupStepFooter, { children: [_jsx(SetupStepBackButton, { onClick: onBack, disabled: creating || !!deletingId }), _jsx("div", { className: "flex-1" }), providers.length > 0 ? (_jsxs(Button, { size: "lg", onClick: handleNextWithExisting, disabled: creating || !!deletingId, className: "min-w-[140px]", children: ["Continue", _jsx(ArrowRight, { className: "ml-2 h-4 w-4", strokeWidth: 1 })] })) : (_jsx(Button, { variant: "ghost", size: "lg", onClick: onSkip, disabled: creating || !!deletingId, children: "Skip for now" }))] }));
    return (_jsxs(_Fragment, { children: [_jsxs(SetupStepLayout, { icon: Server, title: "AI Provider", description: "Connect to an AI service to power your agents.", titleClassName: "mb-2", descriptionClassName: "text-sm leading-relaxed", bodyClassName: "space-y-8", contentFooter: addProviderButton, footer: footer, children: [providers.length > 0 && (_jsxs("div", { className: "space-y-3", children: [_jsxs("button", { type: "button", onClick: () => setConnectedCollapsed((prev) => !prev), className: "flex w-full items-center justify-between px-1 text-left", children: [_jsx("h3", { className: "text-neutral-grey-100 text-[14px] font-medium", children: "Currently Connected" }), connectedCollapsed ? (_jsx(ChevronRight, { strokeWidth: 1, className: "text-neutral-grey-50 h-4 w-4" })) : (_jsx(ChevronDown, { strokeWidth: 1, className: "text-neutral-grey-50 h-4 w-4" }))] }), !connectedCollapsed && (_jsx("div", { className: "grid gap-2", children: providers.map((p) => {
                                    const customBaseUrl = getCustomProviderUrl(p, providerTypes);
                                    return (_jsxs("div", { className: "border-border-default bg-neutral-grey-5/50 flex cursor-default items-center justify-between rounded-lg border p-[12px]", children: [_jsxs("div", { className: "flex min-w-0 cursor-default flex-col pr-4 select-none", children: [_jsx("span", { className: "text-neutral-grey-100 text-sm font-medium", children: p.name }), customBaseUrl && (_jsx("span", { className: "text-neutral-grey-50 mt-0.5 cursor-default font-mono text-[11px] leading-relaxed break-all whitespace-normal", children: customBaseUrl }))] }), _jsx(SimpleIconButton, { label: `Remove ${p.name}`, onClick: (event) => {
                                                    event.stopPropagation();
                                                    handleDelete(p);
                                                }, disabled: deletingId === p.id, className: "text-neutral-grey-50 h-8 w-8 p-0", icon: deletingId === p.id ? (_jsx(RefreshCw, { strokeWidth: 1, className: "h-3.5 w-3.5 animate-spin" })) : (_jsx(DeleteIcon, { size: "md" })) })] }, p.id));
                                }) }))] })), showAddForm && (_jsxs("div", { className: "border-feedback-blue bg-feedback-blue-light/20 animate-in fade-in slide-in-from-top-4 space-y-5 rounded-2xl border p-6 duration-500", children: [_jsxs("div", { className: "mb-1 flex items-center justify-between", children: [_jsx("h3", { className: "text-feedback-blue text-sm font-bold", children: "New Connection" }), providers.length > 0 && (_jsx(Button, { variant: "ghost", size: "sm", onClick: () => {
                                            setShowAddForm(false);
                                            setConnectedCollapsed(false);
                                        }, children: "Cancel" }))] }), _jsxs("div", { className: "space-y-4", children: [_jsxs("div", { className: "space-y-1.5", children: [_jsx("label", { className: "text-neutral-grey-50 ml-1 text-[11px] font-medium tracking-wider", children: "Type" }), _jsx(Select, { value: formData.type, onValueChange: (value) => {
                                                    const type = providerTypes.find((t) => t.providerId === value);
                                                    setFormData({
                                                        ...formData,
                                                        type: value,
                                                        name: type?.displayName || value,
                                                    });
                                                }, options: providerTypes.map((t) => ({
                                                    value: t.providerId,
                                                    label: t.displayName,
                                                })), placeholder: "Select service..." })] }), _jsxs("div", { className: "grid grid-cols-2 gap-4", children: [_jsxs("div", { className: "space-y-1.5", children: [_jsx("label", { className: "text-neutral-grey-50 ml-1 text-[11px] font-medium tracking-wider", children: "Display Name" }), _jsx(Input, { value: formData.name, onChange: (e) => setFormData({ ...formData, name: e.target.value }), placeholder: "e.g. Production", className: "border-feedback-blue focus:ring-feedback-blue bg-white" })] }), _jsxs("div", { className: "space-y-1.5", children: [_jsx("label", { className: "text-neutral-grey-50 ml-1 text-[11px] font-medium tracking-wider", children: "Secret Storage" }), _jsx(Select, { value: formData.secretStorage, onValueChange: (value) => setFormData({
                                                            ...formData,
                                                            secretStorage: value,
                                                        }), options: [
                                                            { value: "sitecore", label: "Sitecore field" },
                                                            {
                                                                value: "connectionStrings",
                                                                label: "ConnectionStrings.config",
                                                            },
                                                        ], placeholder: "Select storage" })] })] }), _jsxs("div", { className: "space-y-1.5", children: [_jsx("label", { className: "text-neutral-grey-50 ml-1 text-[11px] font-medium tracking-wider", children: formData.secretStorage === "sitecore"
                                                    ? "API Key"
                                                    : "Connection String Name" }), _jsx(Input, { type: "text", name: formData.secretStorage === "sitecore"
                                                    ? "provider-config-value"
                                                    : "provider-config-reference", autoComplete: "off", autoCapitalize: "none", spellCheck: false, value: formData.secretStorage === "sitecore"
                                                    ? formData.apiKey
                                                    : formData.connectionString, onChange: (e) => setFormData({
                                                    ...formData,
                                                    apiKey: formData.secretStorage === "sitecore"
                                                        ? e.target.value
                                                        : formData.apiKey,
                                                    connectionString: formData.secretStorage === "connectionStrings"
                                                        ? e.target.value
                                                        : formData.connectionString,
                                                }), placeholder: formData.secretStorage === "sitecore"
                                                    ? "sk-..."
                                                    : "parhelia.ai.provider.<providerId>", className: formData.secretStorage === "sitecore" && formData.apiKey
                                                    ? "border-feedback-blue focus:ring-feedback-blue bg-white [-webkit-text-security:disc]"
                                                    : "border-feedback-blue focus:ring-feedback-blue bg-white" })] }), _jsx("div", { className: "text-neutral-grey-50 text-[11px]", children: formData.secretStorage === "connectionStrings"
                                            ? 'Provide either an API key or a connection-string entry. For the latter, add <add name="parhelia.ai.provider.openrouter" connectionString="ApiKey=..." /> to Sitecore ConnectionStrings.config, then enter its name here. The entry can also contain OAuth credentials; secret values are not stored in Sitecore items.'
                                            : "API key is stored in Sitecore provider settings." }), _jsxs("div", { className: "space-y-1.5", children: [_jsx("label", { className: "text-neutral-grey-50 ml-1 text-[11px] font-medium tracking-wider", children: "Endpoint URL (optional)" }), _jsx(Input, { value: formData.baseUrl, onChange: (e) => setFormData({ ...formData, baseUrl: e.target.value }), placeholder: selectedType?.defaultBaseUrl || "https://...", className: "border-feedback-blue focus:ring-feedback-blue bg-white" })] }), _jsx(Button, { onClick: handleCreate, disabled: creating ||
                                            !formData.name ||
                                            !formData.type ||
                                            (formData.secretStorage === "sitecore" && !formData.apiKey) ||
                                            (formData.secretStorage === "connectionStrings" &&
                                                !formData.connectionString), size: "lg", className: "w-full", children: creating ? (_jsxs(_Fragment, { children: [_jsx(RefreshCw, { strokeWidth: 1, className: "mr-2 h-4 w-4 animate-spin" }), "Connecting..."] })) : (_jsxs(_Fragment, { children: [_jsx(Plus, { className: "mr-2 h-4 w-4", strokeWidth: 1 }), "Connect Service"] })) })] })] })), error && _jsx(SetupStepError, { children: error })] }), _jsx(ConfirmationDialog, { ref: confirmationDialogRef })] }));
}
//# sourceMappingURL=ProviderStep.js.map