import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, useEffect, useCallback, useMemo, useRef, } 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("import");
    const [filterText, setFilterText] = useState("");
    const [selectedModelFromList, setSelectedModelFromList] = useState(null);
    const [importedModelId, setImportedModelId] = useState(null);
    const autoLoadedProviderRef = useRef(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: "text-highlight-100 h-8 w-8" }),
                    iconBg: "bg-highlight-10",
                    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: "text-feedback-green h-8 w-8" }),
                    iconBg: "bg-feedback-green-light",
                    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: "text-feedback-blue h-8 w-8" }),
                    iconBg: "bg-feedback-blue-light",
                    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]);
    useEffect(() => {
        if (view !== "import" || !selectedProviderId)
            return;
        if (autoLoadedProviderRef.current === selectedProviderId)
            return;
        autoLoadedProviderRef.current = selectedProviderId;
        loadProviderModels(selectedProviderId);
    }, [view, selectedProviderId, loadProviderModels]);
    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} ring-neutral-grey-100/5 p-4 ring-1 ring-inset`, children: categoryInfo.icon }), _jsx("h2", { className: "text-neutral-grey-100 mb-2 text-3xl font-bold tracking-tight", children: categoryInfo.title }), _jsx("p", { className: "text-neutral-grey-50 max-w-[280px] text-sm leading-relaxed", 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: "border-feedback-green bg-feedback-green-light/20 shadow-feedback-green/5 mx-auto flex max-w-sm flex-col items-center rounded-[2.5rem] border p-10 shadow-2xl", children: [_jsx("div", { className: "bg-feedback-green shadow-feedback-green/30 ring-feedback-green mb-6 rounded-full p-3 text-white shadow-lg ring-4", children: _jsx(CheckCircle, { className: "h-10 w-10", strokeWidth: 3 }) }), _jsx("h3", { className: "text-neutral-grey-100 mb-2 text-2xl font-black tracking-tight", children: "All Set!" }), _jsx("p", { className: "border-feedback-green text-feedback-green mb-10 inline-flex items-center rounded-full border bg-white px-5 py-2 font-mono text-[13px] font-bold shadow-sm transition-transform hover:scale-105", children: selectedModelFromList?.id }), _jsxs("div", { className: "flex w-full gap-4", children: [_jsx(Button, { variant: "ghost", size: "lg", onClick: handleReplace, className: "flex-1", children: "Change" }), _jsxs(Button, { size: "lg", onClick: handleContinue, className: "flex-[1.5]", 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: "text-neutral-grey-50 ml-1 text-[10px] font-bold tracking-[0.2em]", children: "AI Provider" }), _jsx(Select, { value: selectedProviderId, onValueChange: (id) => {
                                                    setSelectedProviderId(id);
                                                    setSelectedModelFromList(null);
                                                    if (view === "import") {
                                                        autoLoadedProviderRef.current = id;
                                                        loadProviderModels(id);
                                                    }
                                                }, options: providers.map((p) => ({
                                                    value: p.id,
                                                    label: p.name,
                                                })) })] })), _jsxs("div", { className: "border-neutral-grey-100/5 bg-neutral-grey-5 flex rounded-xl border 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"
                                                    ? "text-feedback-blue bg-white shadow-sm"
                                                    : "text-neutral-grey-50 hover:text-neutral-grey-100"}`, 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"
                                                    ? "text-feedback-blue bg-white shadow-sm"
                                                    : "text-neutral-grey-50 hover:text-neutral-grey-100"}`, children: "Import" }))] })] }), 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: "text-neutral-grey-50 ml-1 text-[10px] font-bold tracking-[0.2em]", children: "Model Identifier" }), _jsx(Input, { value: manualName, onChange: (e) => setManualName(e.target.value), placeholder: categoryInfo.placeholder, className: "border-border-default focus:ring-feedback-blue h-11 rounded-xl bg-white" })] }), _jsxs(Button, { size: "lg", onClick: handleCreateManual, disabled: creating || !manualName || !selectedProviderId, className: "w-full", 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: "bg-feedback-blue-light absolute inset-0 animate-ping rounded-full opacity-20" }), _jsx(RefreshCw, { className: "text-feedback-blue relative z-10 h-10 w-10 animate-spin", strokeWidth: 1.5 })] }), _jsx("p", { className: "text-neutral-grey-50 text-[10px] font-bold tracking-widest", 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-neutral-grey-50 text-[10px] font-bold tracking-[0.2em]", children: [filteredProviderModels.length, " Models Found"] }), _jsxs(Button, { variant: "ghost", size: "sm", onClick: () => loadProviderModels(), 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: "border-border-default bg-neutral-grey-5 focus:ring-feedback-blue h-10 rounded-xl pl-4 transition-all focus:bg-white" }) }), _jsx("div", { className: "custom-scrollbar divide-border-default border-border-default max-h-[220px] divide-y overflow-y-auto rounded-2xl border bg-white shadow-inner", children: filteredProviderModels.length === 0 ? (_jsx("div", { className: "text-neutral-grey-50 p-12 text-center text-sm font-medium 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-feedback-blue-light/50 ring-feedback-blue ring-1 ring-inset"
                                                            : "hover:bg-neutral-grey-5"}`, 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-feedback-blue"
                                                                            : "text-neutral-grey-100"}`, children: model.id }), model.description && (_jsx("div", { className: "text-neutral-grey-50 group-hover:text-neutral-grey-50 mt-0.5 truncate text-[11px] transition-colors", 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-feedback-blue"
                                                                        : "text-neutral-grey-15"}`, strokeWidth: 2.5 }) })] }, model.id)))) })] }), selectedModelFromList && (_jsx(Button, { size: "lg", onClick: handleImportModel, disabled: creating, className: "animate-in slide-in-from-bottom-4 w-full duration-500", 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 border-feedback-red bg-feedback-red-light 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 })] }))] }), !importedModelId && (_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, children: [_jsx(ArrowLeft, { className: "mr-2 h-4 w-4" }), "Back"] }), _jsx("div", { className: "flex-1" }), _jsx(Button, { variant: "ghost", size: "lg", onClick: onSkip, disabled: creating, children: "Skip category" }), view === "import" && (_jsx(Button, { variant: "outline", size: "lg", onClick: () => {
                            setView("manual");
                            setSelectedModelFromList(null);
                        }, disabled: creating, children: "Manual Entry" }))] }))] }));
}
//# sourceMappingURL=ModelSelectionStep.js.map