import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useCallback, useState, useMemo, useEffect, useRef, } from "react";
import { Dialog, DialogContent, DialogFooter, } from "../../../components/ui/dialog";
import { Button } from "../../../components/ui/button";
import { CountBadge } from "../../../components/ui/badge";
import { Select } from "../../../components/ui/select";
import { StyledDialogTitle } from "../../../components/ui/styled-dialog-title";
import { SearchInput } from "../../../components/SearchInput";
import { setupWizardService, } from "../../services/setupWizardService";
import { RefreshCw, Upload, Plus, ExternalLink, AlertTriangle, } from "lucide-react";
import { useEditContext } from "../../../editor/client/editContext";
import { Checkbox } from "../../../components/ui/checkbox";
import { LoadingState } from "../../../editor/ui/LoadingState";
const roundsToNonZero = (value, decimals) => {
    if (value === undefined || value === null)
        return false;
    return Number(value.toFixed(decimals)) > 0;
};
const hasUsableImagePricing = (model) => roundsToNonZero(model.pricing?.requestCost, 4) ||
    roundsToNonZero(model.pricing?.imageCost, 4) ||
    roundsToNonZero(model.pricing?.imageOutputCost, 4) ||
    roundsToNonZero(model.pricing?.inputTextTokenCostPerMillion, 2) ||
    roundsToNonZero(model.pricing?.inputImageTokenCostPerMillion, 2) ||
    roundsToNonZero(model.pricing?.outputImageTokenCostPerMillion, 2);
export function ImportModelDialog({ open, onOpenChange, onSuccess, importableProviders, providerTypes = [], }) {
    const editContext = useEditContext();
    const [error, setError] = useState(null);
    // Import from provider state
    const [importProviderId, setImportProviderId] = useState(importableProviders[0]?.id || "");
    const [providerModels, setProviderModels] = useState([]);
    const [loadingProviderModels, setLoadingProviderModels] = useState(false);
    const [selectedModelIds, setSelectedModelIds] = useState(new Set());
    const [importing, setImporting] = useState(false);
    const [importSearchQuery, setImportSearchQuery] = useState("");
    const [importTypeFilter, setImportTypeFilter] = useState("all");
    const [importStatusFilter, setImportStatusFilter] = useState("all");
    // Check if the selected provider uses a static catalog
    const selectedProviderType = useMemo(() => {
        const provider = importableProviders.find((p) => p.id === importProviderId);
        if (!provider)
            return null;
        return providerTypes.find((pt) => pt.providerId === provider.type);
    }, [importProviderId, importableProviders, providerTypes]);
    const isStaticCatalog = selectedProviderType?.isStaticCatalog ?? false;
    // Track previous open state to detect open transitions
    const wasOpenRef = useRef(false);
    // Reset state only when dialog transitions from closed to open
    useEffect(() => {
        if (open && !wasOpenRef.current) {
            setError(null);
            setImportProviderId(importableProviders[0]?.id || "");
            setProviderModels([]);
            setSelectedModelIds(new Set());
            setImportSearchQuery("");
            setImportTypeFilter("all");
            setImportStatusFilter("all");
            setImporting(false);
        }
        wasOpenRef.current = open;
    }, [open, importableProviders]);
    // Automatically load models when provider is selected
    useEffect(() => {
        if (!open || !importProviderId) {
            return;
        }
        let cancelled = false;
        const loadModels = async () => {
            try {
                setLoadingProviderModels(true);
                setError(null);
                const models = await setupWizardService.getProviderModels(importProviderId);
                if (!cancelled) {
                    setProviderModels(models);
                    setSelectedModelIds(new Set());
                }
            }
            catch (e) {
                if (!cancelled) {
                    setError(e?.message || "Failed to load models from provider");
                }
            }
            finally {
                if (!cancelled) {
                    setLoadingProviderModels(false);
                }
            }
        };
        loadModels();
        return () => {
            cancelled = true;
        };
    }, [open, importProviderId]);
    // Load models from provider
    const handleLoadProviderModels = useCallback(async () => {
        if (!importProviderId) {
            setError("Please select a provider first");
            return;
        }
        try {
            setLoadingProviderModels(true);
            setError(null);
            const models = await setupWizardService.getProviderModels(importProviderId);
            setProviderModels(models);
            setSelectedModelIds(new Set());
        }
        catch (e) {
            setError(e?.message || "Failed to load models from provider");
        }
        finally {
            setLoadingProviderModels(false);
        }
    }, [importProviderId]);
    // Filter provider models
    const filteredProviderModels = useMemo(() => {
        return providerModels.filter((model) => {
            // Search filter
            if (importSearchQuery) {
                const query = importSearchQuery.toLowerCase();
                if (!model.id.toLowerCase().includes(query) &&
                    !model.name.toLowerCase().includes(query) &&
                    !model.provider.toLowerCase().includes(query)) {
                    return false;
                }
            }
            // Type filter
            if (importTypeFilter !== "all" && model.modelType !== importTypeFilter) {
                return false;
            }
            // Status filter
            if (importStatusFilter === "missing" && model.isInstalled) {
                return false;
            }
            if (importStatusFilter === "installed" && !model.isInstalled) {
                return false;
            }
            if (importStatusFilter === "pricingDiffers" && !model.pricingDiffers) {
                return false;
            }
            return true;
        });
    }, [providerModels, importSearchQuery, importTypeFilter, importStatusFilter]);
    // Group models by provider
    const groupedProviderModels = useMemo(() => {
        const groups = {};
        filteredProviderModels.forEach((model) => {
            const provider = model.provider || "other";
            if (!groups[provider]) {
                groups[provider] = [];
            }
            groups[provider].push(model);
        });
        // Sort groups by provider name
        return Object.entries(groups).sort(([a], [b]) => a.localeCompare(b));
    }, [filteredProviderModels]);
    // Toggle model selection
    const toggleModelSelection = useCallback((modelId) => {
        setSelectedModelIds((prev) => {
            const next = new Set(prev);
            if (next.has(modelId)) {
                next.delete(modelId);
            }
            else {
                next.add(modelId);
            }
            return next;
        });
    }, []);
    // Import selected models
    const handleImportSelected = useCallback(async () => {
        if (selectedModelIds.size === 0) {
            setError("Please select at least one model to import");
            return;
        }
        try {
            setImporting(true);
            setError(null);
            const result = await setupWizardService.upsertProviderModels({
                providerId: importProviderId,
                selectedModelIds: Array.from(selectedModelIds),
                mode: "createMissing",
            });
            // Update local state optimistically to mark imported models as installed
            // This avoids reloading the entire list and showing the spinner
            if (result.createdCount > 0) {
                setProviderModels((prevModels) => prevModels.map((model) => selectedModelIds.has(model.id)
                    ? { ...model, isInstalled: true, pricingDiffers: false }
                    : model));
            }
            // Clear selection after successful import
            setSelectedModelIds(new Set());
            // Refresh the parent's installed models list
            onSuccess();
            // Show result
            if (result.errors.length > 0) {
                setError(`Created ${result.createdCount} models. Errors: ${result.errors.join(", ")}`);
            }
            else {
                onOpenChange(false);
            }
        }
        catch (e) {
            setError(e?.message || "Failed to import models");
        }
        finally {
            setImporting(false);
        }
    }, [importProviderId, onOpenChange, selectedModelIds, onSuccess]);
    return (_jsx(Dialog, { open: open, onOpenChange: onOpenChange, children: _jsxs(DialogContent, { className: "flex h-[60vh] max-w-3xl flex-col", children: [_jsx(StyledDialogTitle, { icon: _jsx(Upload, { strokeWidth: 1 }), title: "Import Models from Provider" }), _jsxs("div", { className: "flex min-h-0 flex-1 flex-col gap-4 overflow-hidden p-6", children: [_jsxs("div", { className: "grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3", children: [_jsxs("div", { className: "space-y-1.5", children: [_jsx("label", { className: "text-neutral-grey-50 text-xs font-medium tracking-wider", children: "Provider" }), _jsx(Select, { value: importProviderId, onValueChange: (value) => {
                                                setImportProviderId(value);
                                                setProviderModels([]);
                                                setSelectedModelIds(new Set());
                                            }, options: importableProviders.map((provider) => ({
                                                value: provider.id,
                                                label: provider.name,
                                            })), placeholder: "Select provider" })] }), importProviderId && (_jsxs("div", { className: "space-y-1.5", children: [_jsx("label", { className: "text-neutral-grey-50 text-xs font-medium tracking-wider", children: "Model Type" }), _jsx(Select, { value: importTypeFilter, onValueChange: (value) => setImportTypeFilter(value), options: [
                                                { value: "all", label: "All Types" },
                                                { value: "chat", label: "Chat Models" },
                                                { value: "embeddings", label: "Embeddings" },
                                                { value: "image", label: "Image" },
                                            ] })] })), !loadingProviderModels && providerModels.length > 0 && (_jsxs("div", { className: "space-y-1.5", children: [_jsx("label", { className: "text-neutral-grey-50 text-xs font-medium tracking-wider", children: "Status" }), _jsx(Select, { value: importStatusFilter, onValueChange: (value) => setImportStatusFilter(value), options: [
                                                { value: "all", label: "All Status" },
                                                { value: "missing", label: "Not Installed" },
                                                { value: "installed", label: "Installed" },
                                                { value: "pricingDiffers", label: "Pricing Differs" },
                                            ] })] }))] }), (isStaticCatalog || importProviderId) && (_jsxs("div", { className: `flex flex-col gap-2 rounded-lg border p-3 text-xs ${isStaticCatalog
                                ? "border-feedback-orange bg-feedback-orange-light text-feedback-orange"
                                : "border-feedback-blue bg-feedback-blue-light text-feedback-blue"}`, children: [isStaticCatalog && (_jsxs("div", { className: "flex items-start gap-2", children: [_jsx(AlertTriangle, { className: "mt-0.5 h-4 w-4 shrink-0" }), _jsx("p", { children: "This provider's model catalog is maintained manually and may not include the latest models or pricing." })] })), importProviderId && (_jsxs("div", { className: "flex items-start gap-2", children: [_jsx(AlertTriangle, { className: `mt-0.5 h-4 w-4 shrink-0 ${isStaticCatalog ? "text-feedback-orange" : "text-feedback-blue"}` }), _jsx("p", { children: isStaticCatalog
                                                ? "Model availability and pricing for this provider are maintained manually and may lag behind the live provider catalog."
                                                : "Pricing is retrieved from the provider's API and may not be 100% precise. Please verify on the provider's website." })] }))] })), (loadingProviderModels || providerModels.length > 0) && (_jsxs(_Fragment, { children: [!loadingProviderModels && providerModels.length > 0 && (_jsx("div", { className: "flex flex-col gap-3", children: _jsx("div", { className: "flex flex-wrap items-center gap-2", children: _jsx(SearchInput, { value: importSearchQuery, onChange: setImportSearchQuery, className: "min-w-48 flex-1", inputClassName: "border-border-default focus:border-feedback-blue focus:ring-feedback-blue h-10", size: "lg", placeholder: "Search models by name or ID..." }) }) })), _jsx("div", { className: "border-border-default min-h-0 flex-1 overflow-y-auto rounded-xl border bg-white", children: loadingProviderModels ? (_jsx(LoadingState, { variant: "fill", message: "Loading model catalog...", className: "min-h-48", spinnerClassName: "text-neutral-grey-50", textClassName: "text-neutral-grey-50" })) : (_jsxs(_Fragment, { children: [groupedProviderModels.map(([provider, models]) => (_jsxs("div", { className: "border-border-default border-b last:border-0", children: [_jsxs("div", { className: "border-border-default/50 bg-neutral-grey-5/90 text-neutral-grey-50 sticky top-0 z-10 flex items-center justify-between border-b px-4 py-2 text-[11px] font-bold tracking-widest backdrop-blur", children: [_jsx("span", { children: provider }), _jsx(CountBadge, { children: models.length })] }), _jsx("div", { className: "divide-border-default divide-y p-2", children: models.map((model) => (_jsxs("div", { className: "group hover:bg-neutral-grey-5 flex cursor-pointer items-start gap-3 rounded-lg p-3 transition-all", onClick: () => toggleModelSelection(model.id), children: [_jsx("div", { className: "mt-0.5 shrink-0", children: _jsx(Checkbox, { checked: selectedModelIds.has(model.id), onCheckedChange: () => toggleModelSelection(model.id), onClick: (event) => event.stopPropagation(), "aria-label": `Select ${model.name || model.id}` }) }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsxs("div", { className: "flex flex-wrap items-center gap-x-2 gap-y-1", children: [_jsx("span", { className: "text-neutral-grey-100 truncate text-sm font-medium", children: model.name || model.id }), _jsxs("div", { className: "flex flex-wrap gap-1", children: [model.isInstalled && (_jsx("span", { className: "rounded-badge bg-feedback-green-light badge-pad-sm text-2xs text-feedback-green ring-feedback-green/20 inline-flex items-center font-bold ring-1 ring-inset", children: "Installed" })), model.pricingDiffers && (_jsx("span", { className: "rounded-badge bg-feedback-orange-light badge-pad-sm text-2xs text-feedback-orange ring-feedback-orange/20 inline-flex items-center font-bold ring-1 ring-inset", children: "Update available" })), _jsx("span", { className: "rounded-badge bg-neutral-grey-5 badge-pad-sm text-2xs text-neutral-grey-50 inline-flex items-center font-medium", children: model.modelType })] }), model.isInstalled &&
                                                                                    model.installedItemId && (_jsx("button", { onClick: async (e) => {
                                                                                        e.stopPropagation();
                                                                                        await editContext?.loadItem(model.installedItemId);
                                                                                        editContext?.switchWorkspace("editor");
                                                                                    }, className: "text-neutral-grey-50 hover:bg-feedback-blue-light hover:text-feedback-blue ml-auto rounded-md p-1 transition-colors", title: "Load item in editor", children: _jsx(ExternalLink, { className: "h-3.5 w-3.5", strokeWidth: 2 }) }))] }), _jsxs("div", { className: "text-neutral-grey-50 mt-1 flex items-center gap-2 text-[11px] font-medium", children: [model.pricing && (_jsx("div", { className: "flex items-center gap-1.5", children: model.modelType === "image" &&
                                                                                        hasUsableImagePricing(model) ? (_jsxs(_Fragment, { children: [model.pricing.requestCost !==
                                                                                                undefined && (_jsxs("span", { className: "border-border-default bg-neutral-grey-5 badge-pad-sm rounded border", children: ["Request: $", model.pricing.requestCost.toFixed(4)] })), model.pricing.imageCost !==
                                                                                                undefined && (_jsxs("span", { className: "border-border-default bg-neutral-grey-5 badge-pad-sm rounded border", children: ["Image: $", model.pricing.imageCost.toFixed(4)] })), model.pricing.imageOutputCost !==
                                                                                                undefined && (_jsxs("span", { className: "border-border-default bg-neutral-grey-5 badge-pad-sm rounded border", children: ["Out Image: $", model.pricing.imageOutputCost.toFixed(4)] })), model.pricing
                                                                                                .inputTextTokenCostPerMillion !==
                                                                                                undefined && (_jsxs("span", { className: "border-border-default bg-neutral-grey-5 badge-pad-sm rounded border", children: ["In Text: $", model.pricing.inputTextTokenCostPerMillion.toFixed(2), "/M"] })), model.pricing
                                                                                                .inputImageTokenCostPerMillion !==
                                                                                                undefined && (_jsxs("span", { className: "border-border-default bg-neutral-grey-5 badge-pad-sm rounded border", children: ["In Image: $", model.pricing.inputImageTokenCostPerMillion.toFixed(2), "/M"] })), model.pricing
                                                                                                .outputImageTokenCostPerMillion !==
                                                                                                undefined && (_jsxs("span", { className: "border-border-default bg-neutral-grey-5 badge-pad-sm rounded border", children: ["Out Image: $", model.pricing.outputImageTokenCostPerMillion.toFixed(2), "/M"] }))] })) : (_jsxs(_Fragment, { children: [_jsxs("span", { className: "border-border-default bg-neutral-grey-5 badge-pad-sm rounded border", children: ["In: $", model.pricing.inputCostPerMillionTokens?.toFixed(2) || "0.00", "/M"] }), model.pricing
                                                                                                .outputCostPerMillionTokens !==
                                                                                                undefined && (_jsxs("span", { className: "border-border-default bg-neutral-grey-5 badge-pad-sm rounded border", children: ["Out: $", model.pricing.outputCostPerMillionTokens.toFixed(2), "/M"] }))] })) })), model.contextLength && (_jsxs("span", { className: "flex items-center gap-1", children: [_jsx("span", { className: "bg-neutral-grey-10 h-1 w-1 rounded-full" }), (model.contextLength / 1000).toFixed(0), "k context"] })), _jsx("span", { className: "text-neutral-grey-50 ml-auto hidden font-mono text-[10px] sm:block", children: model.id })] })] })] }, model.id))) })] }, provider))), filteredProviderModels.length === 0 && (_jsx("div", { className: "text-neutral-grey-50 py-12 text-center", children: "No models match your filters" }))] })) })] })), error && (_jsx("div", { className: "border-feedback-red bg-feedback-red-light text-feedback-red rounded-md border p-3 text-sm", children: error }))] }), _jsxs(DialogFooter, { className: "border-border-default mt-auto shrink-0 border-t px-6 py-4", children: [_jsx(Button, { variant: "outline", onClick: () => onOpenChange(false), children: "Close" }), _jsxs(Button, { onClick: handleImportSelected, disabled: selectedModelIds.size === 0 || importing, className: "shadow-feedback-blue gap-2 shadow-sm", children: [importing ? (_jsx(RefreshCw, { className: "h-3.5 w-3.5 animate-spin" })) : (_jsx(Plus, { className: "h-3.5 w-3.5" })), "Import selected models (", selectedModelIds.size, ")"] })] })] }) }));
}
export default ImportModelDialog;
//# sourceMappingURL=ImportModelDialog.js.map