import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
/*
 * Copyright (c) 2023-2025 Datalayer, Inc.
 * Distributed under the terms of the Modified BSD License.
 */
import { useCallback, useEffect, useMemo, useState } from 'react';
import { nullTranslator } from '@jupyterlab/translation';
import { ActionList } from '@primer/react';
import { CloudUploadIcon } from '@datalayer/icons-react';
import { useCoreStore, useIAMStore } from '../../state/index.js';
import { isRuntimeRemote } from '../../stateful/runtimes/index.js';
import { RuntimeSnippetsFacade } from '../../stateful/jupyter/index.js';
import { ExternalTokenSilentLogin } from '../../components/iam/index.js';
import { SnippetDialog } from './../snippets/SnippetDialog.js';
import { RuntimeLauncherDialog } from './RuntimeLauncherDialog.js';
import { RuntimePickerBase } from './RuntimePickerBase.js';
import { RuntimeCellVariablesDialog } from './RuntimeCellVariablesDialog.js';
/**
 * Runtime picker component for a cell.
 */
export function RuntimePickerCell(props) {
    const { logIn, markdownParser, model, preference, sanitizer, multiServiceManager, sessionContext, translator, } = props;
    const { token } = useIAMStore();
    const { configuration } = useCoreStore();
    const [isForeign, setIsForeign] = useState(false);
    const [hasCellRuntime, setHasCellRuntime] = useState(false);
    const [isKernelDialogOpen, setIsKernelDialogOpen] = useState(false);
    const [isVariableDialogOpen, setIsVariableDialogOpen] = useState(false);
    const [language, setLanguage] = useState('');
    const [snippets, setSnippets] = useState([]);
    const [isSnippetDialogOpen, setIsSnippetDialogOpen] = useState(false);
    const trans = useMemo(() => (translator ?? nullTranslator).load('jupyterlab'), [translator]);
    useEffect(() => {
        const updateState = (model) => {
            const datalayerMeta = model.getMetadata('datalayer') ?? {};
            const runtime = datalayerMeta.kernel;
            setIsForeign(!!runtime);
            setHasCellRuntime(runtime?.params?.notebook === false);
            const newSnippets = new Array();
            if (runtime) {
                const spec = multiServiceManager.remote?.environments
                    .get()
                    .find(env => env.name === runtime.name);
                setLanguage(spec?.language ?? '');
                if (spec?.snippets) {
                    newSnippets.push(...spec.snippets);
                }
            }
            setSnippets(newSnippets);
        };
        updateState(model);
        model.metadataChanged.connect(updateState);
        return () => {
            model.metadataChanged.disconnect(updateState);
        };
    }, [model]);
    const filterKernel = useCallback((desc) => {
        return (!!desc.kernelId &&
            isRuntimeRemote(desc.location) &&
            (!preference?.language || desc.language === preference?.language));
    }, [preference]);
    const setSelectedRuntimeDesc = useCallback((kernel) => {
        const datalayerMeta = model.getMetadata('datalayer') ?? {
            runtime: undefined,
        };
        if (!kernel) {
            delete datalayerMeta.kernel;
            model.setMetadata('datalayer', datalayerMeta);
        }
        else {
            model.setMetadata('datalayer', Object.assign(datalayerMeta, { kernel }));
        }
    }, [model]);
    const closeVariableDialog = useCallback(() => {
        setIsVariableDialogOpen(false);
    }, []);
    const openVariableDialog = useCallback(() => {
        setIsVariableDialogOpen(true);
    }, []);
    const closeSnippetDialog = useCallback(() => {
        setIsSnippetDialogOpen(false);
    }, []);
    const openSnippetDialog = useCallback(() => {
        setIsSnippetDialogOpen(true);
    }, []);
    const setCell = useCallback(() => {
        setIsKernelDialogOpen(true);
    }, []);
    const onStartRemote = useCallback((desc) => {
        if (desc) {
            desc.params = {
                ...desc.params,
                notebook: false,
            };
            setSelectedRuntimeDesc(desc);
        }
        setIsKernelDialogOpen(false);
    }, [setSelectedRuntimeDesc]);
    const datalayerMeta = model.getMetadata('datalayer') ?? {};
    return (_jsxs(_Fragment, { children: [_jsx(RuntimePickerBase, { display: "menu", filterRuntime: filterKernel, preference: preference, multiServiceManager: multiServiceManager, runtimeDesc: datalayerMeta.kernel ? datalayerMeta.kernel : undefined, setRuntimeDesc: setSelectedRuntimeDesc, variant: 'cell', preActions: _jsxs(ActionList.Item, { disabled: !multiServiceManager.remote, onSelect: setCell, selected: hasCellRuntime, title: !multiServiceManager.remote
                        ? 'You are not connected with Datalayer.'
                        : 'Assign a new temporary Runtime on each Cell execution.', children: [_jsx(ActionList.LeadingVisual, { children: _jsx(CloudUploadIcon, {}) }), trans.__('Assign a Cell Runtime')] }), postActions: token || !logIn ? (_jsxs(_Fragment, { children: [RuntimeSnippetsFacade.supports(preference?.language ?? '') && (_jsx(ActionList.Item, { onSelect: openVariableDialog, disabled: !isForeign, title: trans.__('Define variables to transfer between the document kernel and the cell kernel.'), children: trans.__('Define Cell Variables Transfer') })), !configuration.whiteLabel && (_jsx(ActionList.Item, { onSelect: openSnippetDialog, disabled: snippets.length === 0, title: trans.__('Inject a code snippet at the end of the cell.'), children: trans.__('Inject Code Snippet') }))] })) : (_jsx(ActionList.Item, { onSelect: props.logIn, title: 'Connect to the Runtime provider.', children: _jsx(ExternalTokenSilentLogin, { message: "Connect to the Runtime provider" }) })), translator: translator }), isVariableDialogOpen && (_jsx(RuntimeCellVariablesDialog, { model: model, onClose: closeVariableDialog, preference: preference, sessionContext: sessionContext, translator: translator })), isSnippetDialogOpen && (_jsx(SnippetDialog, { language: language, model: model, snippets: snippets, onClose: closeSnippetDialog, markdownParser: markdownParser, sanitizer: sanitizer })), isKernelDialogOpen && (_jsx(RuntimeLauncherDialog, { manager: multiServiceManager.remote, onSubmit: onStartRemote, startRuntime: false, markdownParser: markdownParser, sanitizer: sanitizer }))] }));
}
export default RuntimePickerCell;
