import $i18n from '../../../../../../locales/i18n.js';
import React, { useState, useCallback, useMemo } from 'react';
import classNames from 'classnames';
import { CnButton, CnIcon, CnTooltip } from '@cainiaofe/cn-ui';
import { event as eventBus } from '@ice/stark-data';
import { useModel } from '../../../../../../utils/mobx-react-simpler/index.js';
import { FieldSelector } from '../../../../../../cn-ai-table/view/components/selectors/field-selector/field-selector';
import { Popup } from '@cainiaofe/cn-domain-popup';
import { useAiColumns } from '../../../../../../cn-ai-table/view/hooks';
import { useCnAiListEventNames } from '../../../../../../cn-ai-agent/context/cn-ai-list-event-context';
import { armsHottagLog } from '../../../../../../utils/arms/arms-hot-tag-log.js';
import { FLOATING_LAYER_Z_INDEX, getPopupContainer } from '../../../../../../utils/floating-layer.js';
import { getFieldSystem } from '../../../../../../cn-ai-table/view/field-system';
import { pickLookupCallbacks } from '../../../../../../cn-ai-table/types';
export function AddFieldButton({ viewId, enableAiFields = true, enableLookup = true, enableFormula = true, }) {
    var _a, _b, _c;
    const cnAiListEventNames = useCnAiListEventNames();
    const dataModel = useModel('dataModel');
    const [selectorVisible, setSelectorVisible] = useState(false);
    const [activeDriverType, setActiveDriverType] = useState(null);
    const [selectedFieldLabel, setSelectedFieldLabel] = useState('');
    const { saveAiColumn, savingAiColumn, executingColumnTask } = useAiColumns({
        tableId: dataModel.tableId,
        enabled: enableAiFields,
        bizRequestConfig: {
            aiColumn: (_a = dataModel.bizRequestConfig) === null || _a === void 0 ? void 0 : _a.aiColumn,
            cubePlatform: (_b = dataModel.bizRequestConfig) === null || _b === void 0 ? void 0 : _b.cubePlatform,
        },
    });
    const { registry, orchestrator } = useMemo(() => getFieldSystem(), []);
    const buildContext = useCallback(() => {
        var _a;
        return {
            dataModel,
            viewId,
            bizRequestConfig: dataModel.bizRequestConfig,
            lookupFieldConfig: (_a = dataModel.lookupFieldConfig) !== null && _a !== void 0 ? _a : undefined,
            eventBus: { emit: (event, payload) => eventBus.emit(event, payload) },
            cnAiListEventNames,
            services: {
                aiColumn: {
                    saveAiColumn,
                    savingAiColumn,
                    executingColumnTask,
                },
                lookup: pickLookupCallbacks(dataModel.lookupFieldConfig),
            },
        };
    }, [dataModel, viewId, cnAiListEventNames, saveAiColumn, savingAiColumn, executingColumnTask]);
    const selectorItems = useMemo(() => {
        let items = registry.getSelectorItems();
        if (!enableAiFields) {
            items = items.filter((item) => item.category !== 'ai' && item.category !== 'agent');
        }
        if (!enableLookup) {
            items = items.filter((item) => item.type !== 'lookup');
        }
        if (!enableFormula) {
            items = items.filter((item) => item.type !== 'formula');
        }
        return items;
    }, [registry, enableAiFields, enableLookup, enableFormula]);
    const resetSelection = useCallback(() => {
        setActiveDriverType(null);
        setSelectedFieldLabel('');
    }, []);
    const closeAll = useCallback(() => {
        setSelectorVisible(false);
        resetSelection();
    }, [resetSelection]);
    const handleFieldSelect = async (fieldType) => {
        const driver = registry.get(fieldType);
        if (!driver)
            return;
        const meta = driver.getMeta();
        const ui = driver.getUiContribution();
        armsHottagLog({
            hottag: 'cn-ai-table.addField.selectField',
            name: $i18n.get({ id: 'SelectField', dm: '选择字段' }),
            c6: fieldType,
        });
        if (ui.panelKind === 'inline' && ui.createPanel) {
            setActiveDriverType(fieldType);
            setSelectedFieldLabel(meta.label);
            setSelectorVisible(false);
        }
        else {
            const result = await orchestrator.createField(fieldType, {}, buildContext());
            if (result.success) {
                closeAll();
            }
        }
    };
    const handleDriverPanelSave = async (config) => {
        if (!activeDriverType)
            return;
        const ctx = buildContext();
        const result = await orchestrator.createField(activeDriverType, config, ctx);
        if (result.success) {
            closeAll();
        }
    };
    const handleDriverPanelCancel = () => {
        if (activeDriverType) {
            const driver = registry.get(activeDriverType);
            const meta = driver === null || driver === void 0 ? void 0 : driver.getMeta();
            if ((meta === null || meta === void 0 ? void 0 : meta.category) === 'ai' || (meta === null || meta === void 0 ? void 0 : meta.category) === 'agent') {
                armsHottagLog({
                    hottag: 'cn-ai-table.addField.cancelAiField',
                    name: $i18n.get({ id: 'UnaddAIField', dm: '取消添加AI字段' }),
                });
            }
            if ((meta === null || meta === void 0 ? void 0 : meta.type) === 'lookup') {
                armsHottagLog({
                    hottag: 'cn-ai-table.addField.cancelLookupField',
                    name: $i18n.get({ id: 'RemoveAddedCitationField', dm: '取消添加引用字段' }),
                });
            }
            if ((meta === null || meta === void 0 ? void 0 : meta.type) === 'formula') {
                armsHottagLog({
                    hottag: 'cn-ai-table.addField.cancelFormulaField',
                    name: $i18n.get({ id: 'CancelAddingFormulaField', dm: '取消添加公式字段' }),
                });
            }
        }
        closeAll();
    };
    const isActive = selectorVisible || activeDriverType !== null;
    const handlePopupOpenChange = (visible) => {
        if (!visible) {
            closeAll();
        }
    };
    const activeDriver = activeDriverType ? registry.get(activeDriverType) : null;
    const ActivePanel = (_c = activeDriver === null || activeDriver === void 0 ? void 0 : activeDriver.getUiContribution().createPanel) !== null && _c !== void 0 ? _c : null;
    const triggerButton = (React.createElement("div", { className: classNames('toolbar-add-btn', {
            'toolbar-add-btn-active': isActive,
        }), onClick: (e) => {
            e.stopPropagation();
            if (!isActive) {
                armsHottagLog({
                    hottag: 'cn-ai-table.addField.open',
                    name: $i18n.get({ id: 'AddField', dm: '添加字段' }),
                });
            }
            if (activeDriverType) {
                closeAll();
            }
            else {
                setSelectorVisible((visible) => {
                    const nextVisible = !visible;
                    if (nextVisible) {
                        armsHottagLog({
                            hottag: 'cn-ai-table.addField.openSelector',
                            name: $i18n.get({ id: 'OpenFieldChooser', dm: '打开字段选择器' }),
                        });
                    }
                    return nextVisible;
                });
            }
        }, style: { cursor: 'pointer' } },
        React.createElement(CnButton, { text: true },
            React.createElement(CnIcon, { type: "add", size: "medium", style: { color: '#fff' } }))));
    const tooltipTrigger = (React.createElement(CnTooltip, { v2: true, triggerType: "hover", align: "b", trigger: triggerButton, popupProps: {
            ...(isActive ? { visible: false } : {}),
            style: { zIndex: FLOATING_LAYER_Z_INDEX },
        } },
        React.createElement("span", { style: { whiteSpace: 'nowrap' } }, $i18n.get({ id: 'AddField', dm: '添加字段' }))));
    return (React.createElement(Popup, { visible: isActive, onVisibleChange: handlePopupOpenChange, container: getPopupContainer, trigger: tooltipTrigger, align: "bl", offset: 10 },
        selectorVisible ? (React.createElement(FieldSelector, { enableAiFields: enableAiFields, items: selectorItems, onSelect: handleFieldSelect })) : null,
        ActivePanel && activeDriverType ? (React.createElement(ActivePanel, { fieldType: activeDriverType, fieldLabel: selectedFieldLabel, context: buildContext(), onSave: handleDriverPanelSave, onCancel: handleDriverPanelCancel })) : null));
}
