import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, useEffect, useCallback, useMemo } 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 { Brain, Image, Hash, RefreshCw, AlertCircle, Cloud, CheckCircle, ArrowRight, ArrowLeft, } from "lucide-react";
export function ModelSelectionStep({ category, providerId: initialProviderId, onNext, onSkip, onBack, }) {
    const [loading, setLoading] = useState(false);
    const [providerModels, setProviderModels] = useState([]);
    const [providers, setProviders] = useState([]);
    const [selectedProviderId, setSelectedProviderId] = useState(initialProviderId);
    const [error, setError] = useState(null);
    const [manualName, setManualName] = useState("");
    const [creating, setCreating] = useState(false);
    const [view, setView] = useState("manual");
    const [filterText, setFilterText] = useState("");
    const [selectedModelFromList, setSelectedModelFromList] = useState(null);
    const [importedModelId, setImportedModelId] = useState(null);
    useEffect(() => {
        // 1. Load providers
        setupWizardService
            .getProviders()
            .then((p) => {
            setProviders(p);
            if (!selectedProviderId && p && p.length > 0) {
                setSelectedProviderId(p[0]?.id);
            }
        })
            .catch((e) => setError(e?.message || "Failed to load providers"));
        // 2. Check if a model is already configured for this category
        const checkExisting = async () => {
            try {
                const normalizeId = (id) => id.replace(/[{}()]/g, "").toLowerCase();
                if (category === "embeddings") {
                    const config = await setupWizardService.getEmbeddingsConfig();
                    if (config.modelId) {
                        const normId = normalizeId(config.modelId);
                        const installedModels = await setupWizardService.getInstalledModels();
                        const model = installedModels.find((m) => normalizeId(m.id) === normId);
                        if (model) {
                            setImportedModelId(model.id);
                            setSelectedModelFromList({
                                id: model.name || model.key,
                                name: model.name,
                                modelType: "embeddings",
                                provider: model.providerName || "",
                                inputModalities: [],
                                outputModalities: [],
                                isInstalled: true,
                                installedItemId: model.id,
                                pricingDiffers: false,
                            });
                        }
                    }
                }
                else {
                    const defaults = await setupWizardService.getDefaultModels();
                    const rawId = category === "chat" ? defaults.chatModelId : defaults.imageModelId;
                    if (rawId) {
                        const normId = normalizeId(rawId);
                        const installedModels = await setupWizardService.getInstalledModels();
                        const model = installedModels.find((m) => normalizeId(m.id) === normId);
                        if (model) {
                            setImportedModelId(model.id);
                            setSelectedModelFromList({
                                id: model.name || model.key,
                                name: model.name,
                                modelType: category,
                                provider: model.providerName || "",
                                inputModalities: [],
                                outputModalities: [],
                                isInstalled: true,
                                installedItemId: model.id,
                                pricingDiffers: false,
                            });
                        }
                    }
                }
            }
            catch (e) {
                console.warn("Failed to check existing configuration", e);
            }
        };
        checkExisting();
    }, [initialProviderId, category]);
    const categoryInfo = useMemo(() => {
        switch (category) {
            case "chat":
                return {
                    title: "Set Default Chat Model",
                    description: "This model will be used for general chat and content generation.",
                    icon: _jsx(Brain, { className: "h-8 w-8 text-purple-600" }),
                    iconBg: "bg-purple-50",
                    templateType: "Ai Chat Model",
                    placeholder: "e.g. gpt-4o",
                };
            case "image":
                return {
                    title: "Set Default Image Model",
                    description: "This model will be used for image generation and editing.",
                    icon: _jsx(Image, { className: "h-8 w-8 text-green-600" }),
                    iconBg: "bg-green-50",
                    templateType: "Ai Image Model",
                    placeholder: "e.g. dall-e-3",
                };
            case "embeddings":
                return {
                    title: "Set Default Embeddings Model",
                    description: "Used for semantic search and content indexing.",
                    icon: _jsx(Hash, { className: "h-8 w-8 text-blue-600" }),
                    iconBg: "bg-blue-50",
                    templateType: "Ai Embeddings Model",
                    placeholder: "e.g. text-embedding-3-small",
                };
        }
    }, [category]);
    const loadProviderModels = useCallback(async (pId) => {
        const id = pId || selectedProviderId;
        if (!id)
            return;
        try {
            setLoading(true);
            setError(null);
            const models = await setupWizardService.getProviderModels(id);
            setProviderModels(models);
            setView("import");
        }
        catch (e) {
            setError(e?.message || "Failed to fetch models from provider");
            setView("manual");
        }
        finally {
            setLoading(false);
        }
    }, [selectedProviderId, category]);
    const filteredProviderModels = useMemo(() => {
        const categoryModels = providerModels.filter((m) => m.modelType?.toLowerCase() === category.toLowerCase());
        if (!filterText.trim())
            return categoryModels;
        const term = filterText.toLowerCase();
        return categoryModels.filter((m) => m.id.toLowerCase().includes(term) ||
            m.description?.toLowerCase().includes(term));
    }, [providerModels, filterText, category]);
    const handleCreateManual = useCallback(async () => {
        if (!manualName || !selectedProviderId)
            return;
        try {
            setCreating(true);
            setError(null);
            const modelId = await setupWizardService.createModel({
                templateType: categoryInfo.templateType,
                modelName: manualName,
                providerId: selectedProviderId,
            });
            onNext(modelId);
        }
        catch (e) {
            setError(e?.message || "Failed to create model");
        }
        finally {
            setCreating(false);
        }
    }, [manualName, selectedProviderId, categoryInfo, onNext]);
    const handleImportModel = useCallback(async () => {
        if (!selectedProviderId || !selectedModelFromList)
            return;
        try {
            setCreating(true);
            setError(null);
            const result = await setupWizardService.upsertProviderModels({
                providerId: selectedProviderId,
                selectedModelIds: [selectedModelFromList.id],
                mode: "createMissing",
            });
            if (result.errors.length > 0) {
                throw new Error(result.errors[0]);
            }
            const installedModels = await setupWizardService.getInstalledModels();
            const installed = installedModels.find((m) => m.name === selectedModelFromList.id);
            if (installed) {
                setImportedModelId(installed.id);
            }
            else {
                throw new Error("Model imported but could not find the new item");
            }
        }
        catch (e) {
            setError(e?.message || "Failed to import model");
        }
        finally {
            setCreating(false);
        }
    }, [selectedProviderId, selectedModelFromList]);
    const handleContinue = () => {
        if (importedModelId) {
            onNext(importedModelId);
        }
    };
    const handleReplace = () => {
        setImportedModelId(null);
        setSelectedModelFromList(null);
    };
    return (_jsxs("div", { className: "mx-auto flex h-full max-w-xl flex-col p-10", children: [_jsxs("div", { className: "mb-8 flex shrink-0 flex-col items-center text-center", children: [_jsx("div", { className: `mb-4 rounded-2xl ${categoryInfo.iconBg} p-4 ring-1 ring-black/5 ring-inset`, children: categoryInfo.icon }), _jsx("h2", { className: "mb-2 text-3xl font-bold tracking-tight text-gray-900", children: categoryInfo.title }), _jsx("p", { className: "max-w-[280px] text-sm leading-relaxed text-gray-500", children: categoryInfo.description })] }), _jsxs("div", { className: "min-h-0 flex-1 space-y-6 overflow-y-auto px-1 py-2", children: [importedModelId ? (_jsx("div", { className: "animate-in fade-in zoom-in space-y-6 py-12 text-center duration-500", children: _jsxs("div", { className: "mx-auto flex max-w-sm flex-col items-center rounded-[2.5rem] border border-green-100 bg-green-50/20 p-10 shadow-2xl shadow-green-900/5", children: [_jsx("div", { className: "mb-6 rounded-full bg-green-500 p-3 text-white shadow-lg ring-4 shadow-green-500/30 ring-green-100", children: _jsx(CheckCircle, { className: "h-10 w-10", strokeWidth: 3 }) }), _jsx("h3", { className: "mb-2 text-2xl font-black tracking-tight text-gray-900", children: "All Set!" }), _jsx("p", { className: "mb-10 inline-flex items-center rounded-full border border-green-100 bg-white px-5 py-2 font-mono text-[13px] font-bold text-green-600 shadow-sm transition-transform hover:scale-105", children: selectedModelFromList?.id }), _jsxs("div", { className: "flex w-full gap-4", children: [_jsx(Button, { variant: "ghost", onClick: handleReplace, className: "h-10 flex-1 rounded-full text-[10px] font-bold tracking-[0.2em] text-gray-400 uppercase hover:bg-gray-100 hover:text-gray-600", children: "Change" }), _jsxs(Button, { onClick: handleContinue, className: "h-10 flex-[1.5] rounded-full bg-blue-600 text-[10px] font-black tracking-[0.2em] text-white uppercase shadow-xl shadow-blue-600/20 transition-all hover:bg-blue-700 active:scale-95", children: ["Continue", _jsx(ArrowRight, { className: "ml-2 h-3.5 w-3.5", strokeWidth: 3 })] })] })] }) })) : (_jsxs(_Fragment, { children: [_jsxs("div", { className: "grid gap-4", children: [providers.length > 0 && (_jsxs("div", { className: "space-y-1.5", children: [_jsx("label", { className: "ml-1 text-[10px] font-bold tracking-[0.2em] text-gray-400 uppercase", children: "AI Provider" }), _jsx(Select, { value: selectedProviderId, onValueChange: (id) => {
                                                    setSelectedProviderId(id);
                                                    setSelectedModelFromList(null);
                                                    if (view === "import") {
                                                        loadProviderModels(id);
                                                    }
                                                }, options: providers.map((p) => ({
                                                    value: p.id,
                                                    label: p.name,
                                                })) })] })), _jsxs("div", { className: "flex rounded-xl border border-black/5 bg-gray-100 p-1 shadow-inner", children: [_jsx("button", { onClick: () => {
                                                    setView("manual");
                                                    setSelectedModelFromList(null);
                                                }, className: `flex-1 rounded-lg py-2 text-xs font-bold transition-all duration-300 ${view === "manual"
                                                    ? "bg-white text-blue-600 shadow-sm"
                                                    : "text-gray-500 hover:text-gray-700"}`, children: "Manual Entry" }), selectedProviderId && (_jsx("button", { onClick: () => {
                                                    setView("import");
                                                    if (providerModels.length === 0)
                                                        loadProviderModels();
                                                }, className: `flex-1 rounded-lg py-2 text-xs font-bold transition-all duration-300 ${view === "import"
                                                    ? "bg-white text-blue-600 shadow-sm"
                                                    : "text-gray-500 hover:text-gray-700"}`, children: "Import from API" }))] })] }), view === "manual" ? (_jsxs("div", { className: "animate-in fade-in slide-in-from-bottom-2 space-y-4", children: [_jsxs("div", { className: "space-y-1.5", children: [_jsx("label", { className: "ml-1 text-[10px] font-bold tracking-[0.2em] text-gray-400 uppercase", children: "Model Identifier" }), _jsx(Input, { value: manualName, onChange: (e) => setManualName(e.target.value), placeholder: categoryInfo.placeholder, className: "h-11 rounded-xl border-gray-200 bg-white focus:ring-blue-500" })] }), _jsxs(Button, { onClick: handleCreateManual, disabled: creating || !manualName || !selectedProviderId, className: "h-10 w-full rounded-xl text-[10px] font-black tracking-[0.2em] uppercase shadow-lg shadow-blue-500/10 transition-all active:scale-95", children: [creating ? (_jsx(RefreshCw, { className: "mr-2 h-4 w-4 animate-spin" })) : null, "Set ", category.charAt(0).toUpperCase() + category.slice(1), " ", "Model"] })] })) : (_jsx("div", { className: "animate-in fade-in slide-in-from-bottom-2 space-y-4", children: loading ? (_jsxs("div", { className: "flex flex-col items-center py-16", children: [_jsxs("div", { className: "relative mb-4", children: [_jsx("div", { className: "absolute inset-0 animate-ping rounded-full bg-blue-100 opacity-20" }), _jsx(RefreshCw, { className: "relative z-10 h-10 w-10 animate-spin text-blue-600", strokeWidth: 1.5 })] }), _jsx("p", { className: "text-[10px] font-bold tracking-widest text-gray-400 uppercase", children: "Fetching Catalog" })] })) : (_jsxs("div", { className: "space-y-4", children: [_jsxs("div", { className: "space-y-2", children: [_jsxs("div", { className: "flex items-center justify-between px-1", children: [_jsxs("span", { className: "text-[10px] font-bold tracking-[0.2em] text-gray-400 uppercase", children: [filteredProviderModels.length, " Models Found"] }), _jsxs(Button, { variant: "ghost", size: "sm", onClick: () => loadProviderModels(), className: "h-6 rounded-full px-3 text-[10px] font-bold tracking-wider text-blue-600 uppercase hover:bg-blue-50", children: [_jsx(RefreshCw, { className: "mr-1 h-3 w-3" }), "Sync"] })] }), _jsx("div", { className: "group relative", children: _jsx(Input, { placeholder: `Search for a model...`, value: filterText, onChange: (e) => setFilterText(e.target.value), className: "h-10 rounded-xl border-gray-200 bg-gray-50 pl-4 transition-all focus:bg-white focus:ring-blue-500" }) }), _jsx("div", { className: "custom-scrollbar max-h-[220px] divide-y divide-gray-100 overflow-y-auto rounded-2xl border border-gray-100 bg-white shadow-inner", children: filteredProviderModels.length === 0 ? (_jsx("div", { className: "p-12 text-center text-sm font-medium text-gray-400 italic", children: providerModels.length === 0
                                                            ? `No ${category} models found.`
                                                            : "No models match your search." })) : (filteredProviderModels.map((model) => (_jsxs("button", { onClick: () => setSelectedModelFromList(model), disabled: creating, className: `group flex w-full items-center justify-between px-4 py-3.5 text-left transition-all disabled:opacity-50 ${selectedModelFromList?.id === model.id
                                                            ? "bg-blue-50/50 ring-1 ring-blue-200 ring-inset"
                                                            : "hover:bg-gray-50"}`, children: [_jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("div", { className: `truncate text-sm font-bold transition-colors ${selectedModelFromList?.id === model.id
                                                                            ? "text-blue-700"
                                                                            : "text-gray-900"}`, children: model.id }), model.description && (_jsx("div", { className: "mt-0.5 truncate text-[11px] text-gray-400 transition-colors group-hover:text-gray-500", children: model.description }))] }), _jsx("div", { className: `ml-4 transition-all duration-300 ${selectedModelFromList?.id === model.id
                                                                    ? "scale-110"
                                                                    : "scale-75 opacity-0 group-hover:scale-90 group-hover:opacity-100"}`, children: _jsx(CheckCircle, { className: `h-5 w-5 ${selectedModelFromList?.id === model.id
                                                                        ? "text-blue-600"
                                                                        : "text-gray-200"}`, strokeWidth: 2.5 }) })] }, model.id)))) })] }), selectedModelFromList && (_jsx(Button, { onClick: handleImportModel, disabled: creating, className: "animate-in slide-in-from-bottom-4 h-10 w-full rounded-xl text-[10px] font-black tracking-[0.2em] uppercase shadow-xl shadow-blue-600/10 transition-all duration-500 active:scale-[0.98]", children: creating ? (_jsxs(_Fragment, { children: [_jsx(RefreshCw, { className: "mr-2 h-4 w-4 animate-spin" }), "Importing..."] })) : (_jsxs(_Fragment, { children: [_jsx(Cloud, { className: "mr-2 h-4 w-4", strokeWidth: 2.5 }), "Import ", selectedModelFromList.id.split("/").pop()] })) }))] })) }))] })), error && (_jsxs("div", { className: "animate-shake flex items-start gap-3 rounded-xl border border-red-100 bg-red-50 p-4", children: [_jsx(AlertCircle, { className: "h-5 w-5 shrink-0 text-red-600" }), _jsx("p", { className: "text-xs leading-relaxed font-medium text-red-800", children: error })] }))] }), !importedModelId && (_jsxs("div", { className: "mt-auto flex shrink-0 items-center gap-3 border-t border-gray-100 pt-6", children: [_jsxs(Button, { variant: "ghost", onClick: onBack, disabled: creating, className: "h-10 rounded-full px-6 text-[10px] font-bold tracking-[0.2em] text-gray-400 uppercase hover:text-gray-600", children: [_jsx(ArrowLeft, { className: "mr-2 h-4 w-4" }), "Back"] }), _jsx("div", { className: "flex-1" }), _jsx(Button, { variant: "ghost", onClick: onSkip, disabled: creating, className: "h-10 rounded-full px-6 text-[10px] font-bold tracking-[0.2em] text-gray-400 uppercase hover:text-gray-600", children: "Skip category" }), view === "import" && (_jsx(Button, { variant: "outline", onClick: () => {
                            setView("manual");
                            setSelectedModelFromList(null);
                        }, disabled: creating, className: "h-10 rounded-full border-gray-200 text-[10px] font-bold tracking-[0.2em] text-gray-500 uppercase hover:text-gray-700", children: "Manual Entry" }))] }))] }));
}
//# sourceMappingURL=ModelSelectionStep.js.map