import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, useEffect, useMemo, useCallback } from "react";
import { Button } from "../../../components/ui/button";
import { Input } from "../../../components/ui/input";
import { Select } from "../../../components/ui/select";
import { setupWizardService, } from "../../../setup/services/setupWizardService";
import { Server, RefreshCw, AlertCircle, ArrowRight, ArrowLeft, Plus, Trash2, ChevronDown, ChevronRight } from "lucide-react";
export function ProviderStep({ onNext, onSkip, onBack }) {
    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(async (id) => {
        try {
            setDeletingId(id);
            await setupWizardService.deleteProvider(id);
            await loadData();
        }
        catch (e) {
            setError(e?.message || "Failed to delete provider");
        }
        finally {
            setDeletingId(null);
        }
    }, [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, { className: "h-8 w-8 animate-spin text-blue-600 mb-4" }), _jsx("p", { className: "text-gray-600", children: "Loading AI providers..." })] }));
    }
    return (_jsxs("div", { className: "mx-auto flex h-[80vh] max-h-[80vh] max-w-xl flex-col p-10 min-h-0 overflow-hidden", children: [_jsxs("div", { className: "flex flex-col items-center text-center mb-8 shrink-0", children: [_jsx("div", { className: "mb-4 rounded-2xl bg-blue-50 p-4 ring-1 ring-blue-100", children: _jsx(Server, { className: "h-10 w-10 text-blue-600", strokeWidth: 1.5 }) }), _jsx("h2", { className: "text-3xl font-bold text-gray-900 mb-2 tracking-tight", children: "AI Provider" }), _jsx("p", { className: "text-gray-500 text-sm leading-relaxed", children: "Connect to an AI service to power your assistants and generation tools." })] }), _jsxs("div", { className: "space-y-8 flex-1 overflow-y-auto min-h-0 px-1 py-2 pb-4", 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-[10px] font-bold text-gray-400 uppercase tracking-[0.2em]", children: "Currently Connected" }), connectedCollapsed ? (_jsx(ChevronRight, { className: "h-4 w-4 text-gray-400" })) : (_jsx(ChevronDown, { className: "h-4 w-4 text-gray-400" }))] }), !connectedCollapsed && (_jsx("div", { className: "grid gap-2", children: providers.map(p => (_jsxs("div", { className: "group flex items-center justify-between p-3 rounded-xl border border-gray-100 bg-gray-50/50 hover:bg-white hover:border-blue-200 hover:shadow-md hover:shadow-blue-500/5 transition-all duration-300", children: [_jsxs("div", { className: "flex flex-col min-w-0 pr-4", children: [_jsx("span", { className: "font-semibold text-gray-900 text-sm", children: p.name }), _jsx("span", { className: "text-[11px] text-gray-400 truncate font-mono mt-0.5", children: p.baseUrl })] }), _jsx(Button, { variant: "ghost", size: "sm", onClick: () => handleDelete(p.id), disabled: deletingId === p.id, className: "h-8 w-8 p-0 text-gray-300 hover:text-red-500 hover:bg-red-50 rounded-lg shrink-0 opacity-0 group-hover:opacity-100 transition-opacity", children: deletingId === p.id ? (_jsx(RefreshCw, { className: "h-3.5 w-3.5 animate-spin" })) : (_jsx(Trash2, { className: "h-3.5 w-3.5", strokeWidth: 2 })) })] }, p.id))) }))] })), !showAddForm ? (_jsxs(Button, { variant: "outline", className: "w-full h-14 flex items-center justify-center gap-2 border-dashed border-gray-200 hover:border-blue-400 hover:bg-blue-50/50 hover:text-blue-600 rounded-xl transition-all", onClick: () => {
                            setConnectedCollapsed(true);
                            setShowAddForm(true);
                        }, children: [_jsx(Plus, { className: "h-4 w-4", strokeWidth: 2.5 }), _jsx("span", { className: "text-sm font-semibold", children: "Add Another Provider" })] })) : (_jsxs("div", { className: "rounded-2xl border border-blue-100 bg-blue-50/20 p-6 space-y-5 animate-in fade-in slide-in-from-top-4 duration-500", children: [_jsxs("div", { className: "flex items-center justify-between mb-1", children: [_jsx("h3", { className: "text-sm font-bold text-blue-900", children: "New Connection" }), providers.length > 0 && (_jsx(Button, { variant: "ghost", size: "sm", onClick: () => {
                                            setShowAddForm(false);
                                            setConnectedCollapsed(false);
                                        }, className: "h-7 text-xs text-blue-600 hover:bg-blue-100 rounded-full", children: "Cancel" }))] }), _jsxs("div", { className: "space-y-4", children: [_jsxs("div", { className: "space-y-1.5", children: [_jsx("label", { className: "text-[11px] font-bold text-gray-500 uppercase tracking-wider ml-1", 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-[11px] font-bold text-gray-500 uppercase tracking-wider ml-1", children: "Display Name" }), _jsx(Input, { value: formData.name, onChange: (e) => setFormData({ ...formData, name: e.target.value }), placeholder: "e.g. Production", className: "bg-white border-blue-100 focus:ring-blue-500" })] }), _jsxs("div", { className: "space-y-1.5", children: [_jsx("label", { className: "text-[11px] font-bold text-gray-500 uppercase tracking-wider ml-1", 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-[11px] font-bold text-gray-500 uppercase tracking-wider ml-1", children: formData.secretStorage === "sitecore"
                                                    ? "API Key"
                                                    : "Connection String Name" }), _jsx(Input, { type: formData.secretStorage === "sitecore" ? "password" : "text", 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: "bg-white border-blue-100 focus:ring-blue-500" })] }), _jsx("div", { className: "text-[11px] text-gray-500", children: formData.secretStorage === "connectionStrings"
                                            ? "Use a key or OAuth credentials from Sitecore ConnectionStrings.config. 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-[11px] font-bold text-gray-500 uppercase tracking-wider ml-1", children: "Endpoint URL (optional)" }), _jsx(Input, { value: formData.baseUrl, onChange: (e) => setFormData({ ...formData, baseUrl: e.target.value }), placeholder: selectedType?.defaultBaseUrl || "https://...", className: "bg-white border-blue-100 focus:ring-blue-500" })] }), _jsx(Button, { onClick: handleCreate, disabled: creating ||
                                            !formData.name ||
                                            !formData.type ||
                                            (formData.secretStorage === "sitecore" && !formData.apiKey) ||
                                            (formData.secretStorage === "connectionStrings" && !formData.connectionString), className: "w-full h-10 rounded-xl shadow-lg shadow-blue-500/10 transition-all active:scale-[0.98] text-xs font-black uppercase tracking-widest bg-blue-600 hover:bg-blue-700 text-white", children: creating ? (_jsxs(_Fragment, { children: [_jsx(RefreshCw, { className: "mr-2 h-4 w-4 animate-spin" }), "Connecting..."] })) : (_jsxs(_Fragment, { children: [_jsx(Plus, { className: "mr-2 h-4 w-4", strokeWidth: 3 }), "Connect Service"] })) })] })] })), error && (_jsxs("div", { className: "flex items-start gap-3 rounded-xl border border-red-100 bg-red-50 p-4 animate-shake", children: [_jsx(AlertCircle, { className: "h-5 w-5 shrink-0 text-red-600" }), _jsx("p", { className: "text-xs text-red-800 leading-relaxed font-medium", children: error })] }))] }), _jsxs("div", { className: "flex items-center gap-3 pt-6 shrink-0 mt-auto border-t border-gray-100", children: [_jsxs(Button, { variant: "ghost", onClick: onBack, disabled: creating || !!deletingId, className: "rounded-full h-10 px-6 text-xs font-bold uppercase tracking-widest text-gray-400", children: [_jsx(ArrowLeft, { className: "mr-2 h-4 w-4" }), "Back"] }), _jsx("div", { className: "flex-1" }), providers.length > 0 ? (_jsxs(Button, { onClick: handleNextWithExisting, disabled: creating || !!deletingId, className: "min-w-[140px] h-10 rounded-full shadow-md shadow-blue-500/10 text-xs font-black uppercase tracking-widest bg-blue-600 hover:bg-blue-700 text-white", children: ["Continue", _jsx(ArrowRight, { className: "ml-2 h-4 w-4", strokeWidth: 3 })] })) : (_jsx(Button, { variant: "ghost", onClick: onSkip, disabled: creating || !!deletingId, className: "rounded-full h-10 text-xs font-bold uppercase tracking-widest text-gray-400", children: "Skip for now" }))] })] }));
}
//# sourceMappingURL=ProviderStep.js.map