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, ChevronDown, ChevronRight, } from "lucide-react";
import { DeleteIcon } from "../../../components/ui/delete-icon";
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: "text-feedback-blue mb-4 h-8 w-8 animate-spin" }), _jsx("p", { className: "text-neutral-grey-50", children: "Loading AI providers..." })] }));
    }
    return (_jsxs("div", { className: "mx-auto flex h-[80vh] max-h-[80vh] min-h-0 max-w-xl flex-col overflow-hidden p-10", children: [_jsxs("div", { className: "mb-8 flex shrink-0 flex-col items-center text-center", children: [_jsx("div", { className: "bg-feedback-blue-light ring-feedback-blue mb-4 rounded-2xl p-4 ring-1", children: _jsx(Server, { className: "text-feedback-blue h-10 w-10", strokeWidth: 1.5 }) }), _jsx("h2", { className: "text-neutral-grey-100 mb-2 text-3xl font-bold tracking-tight", children: "AI Provider" }), _jsx("p", { className: "text-neutral-grey-50 text-sm leading-relaxed", children: "Connect to an AI service to power your assistants and generation tools." })] }), _jsxs("div", { className: "min-h-0 flex-1 space-y-8 overflow-y-auto 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-neutral-grey-50 text-[10px] font-bold tracking-[0.2em]", children: "Currently Connected" }), connectedCollapsed ? (_jsx(ChevronRight, { className: "text-neutral-grey-50 h-4 w-4" })) : (_jsx(ChevronDown, { className: "text-neutral-grey-50 h-4 w-4" }))] }), !connectedCollapsed && (_jsx("div", { className: "grid gap-2", children: providers.map((p) => (_jsxs("div", { className: "group border-border-default bg-neutral-grey-5/50 hover:border-feedback-blue hover:shadow-feedback-blue/5 flex items-center justify-between rounded-xl border p-3 transition-all duration-300 hover:bg-white hover:shadow-md", children: [_jsxs("div", { className: "flex min-w-0 flex-col pr-4", children: [_jsx("span", { className: "text-neutral-grey-100 text-sm font-semibold", children: p.name }), _jsx("span", { className: "text-neutral-grey-50 mt-0.5 truncate font-mono text-[11px]", children: p.baseUrl })] }), _jsx(Button, { variant: "ghost", size: "sm", onClick: () => handleDelete(p.id), disabled: deletingId === p.id, className: "text-neutral-grey-50 hover:bg-neutral-grey-5 hover:text-neutral-grey-50 h-8 w-8 shrink-0 rounded-lg p-0 opacity-0 transition-opacity group-hover:opacity-100", children: deletingId === p.id ? (_jsx(RefreshCw, { className: "h-3.5 w-3.5 animate-spin" })) : (_jsx(DeleteIcon, { size: "md" })) })] }, p.id))) }))] })), !showAddForm ? (_jsxs(Button, { variant: "outline", className: "border-border-default hover:border-feedback-blue hover:bg-feedback-blue-light/50 hover:text-feedback-blue flex h-14 w-full items-center justify-center gap-2 rounded-xl border-dashed 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: "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-semibold 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-semibold 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-semibold 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-semibold tracking-wider", 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: "border-feedback-blue focus:ring-feedback-blue bg-white" })] }), _jsx("div", { className: "text-neutral-grey-50 text-[11px]", 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-neutral-grey-50 ml-1 text-[11px] font-semibold 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, { 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: "border-feedback-red bg-feedback-red-light animate-shake flex items-start gap-3 rounded-xl border p-4", children: [_jsx(AlertCircle, { className: "text-feedback-red h-5 w-5 shrink-0" }), _jsx("p", { className: "text-feedback-red text-xs leading-relaxed font-medium", children: error })] }))] }), _jsxs("div", { className: "border-border-default mt-auto flex shrink-0 items-center gap-3 border-t pt-6", children: [_jsxs(Button, { variant: "ghost", size: "lg", onClick: onBack, disabled: creating || !!deletingId, children: [_jsx(ArrowLeft, { className: "mr-2 h-4 w-4" }), "Back"] }), _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: 3 })] })) : (_jsx(Button, { variant: "ghost", size: "lg", onClick: onSkip, disabled: creating || !!deletingId, children: "Skip for now" }))] })] }));
}
//# sourceMappingURL=ProviderStep.js.map