import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
import { ArrowDown, ArrowLeft, ArrowRight, ArrowUp, EllipsisVertical, TrashBin, Xmark, } from '@gravity-ui/icons';
import { Button, DropdownMenu, Icon, Portal } from '@gravity-ui/uikit';
// @ts-ignore // TODO: fix cjs build
import { findParentNodeClosestToPos } from 'prosemirror-utils';
import { cn } from "../../../../../classname.js";
import { bindActions } from "../../../../../core/index.js";
import { i18n } from "../../../../../i18n/yfm-table/index.js";
import { ErrorLoggerBoundary } from "../../../../../react-utils/ErrorBoundary.js";
import { getTableDimensions, isTableNode } from "../../../../../table-utils/index.js";
import { getChildByNode } from "../../../../../utils/node-children.js";
import { getChildrenOfNode } from "../../../../../utils/nodes.js";
import { getReactRendererFromState } from "../../../../behavior/ReactRenderer/index.js";
import { YfmTableAttr } from "../../const.js";
import { controlActions } from "./actions.js";
import "./yfmTableCellView.css";
export const yfmTableCellCn = cn('table-cell-view');
const b = yfmTableCellCn;
const Controls = function Controls({ columnNumber, rowNumber, view, getParentTable, isInFirstRow, isFirstInRow, }) {
    const actions = bindActions(controlActions)(view);
    const controls = [];
    if (isFirstInRow) {
        controls.push(_jsx(DropdownMenu, { switcherWrapperClassName: b('left-button'), renderSwitcher: (props) => (_jsx(Button, { view: 'outlined', size: 's', ...props, children: _jsx(Icon, { data: EllipsisVertical }) })), items: [
                {
                    text: i18n('row.add.before'),
                    action: () => actions.appendRow.run({
                        tablePos: getParentTable()?.pos,
                        rowNumber,
                        direction: 'before',
                    }),
                    iconStart: _jsx(Icon, { data: ArrowUp }),
                    disabled: !actions.appendRow.isEnable({
                        tablePos: getParentTable()?.pos,
                        rowNumber,
                        direction: 'before',
                    }),
                },
                {
                    text: i18n('row.add.after'),
                    action: () => actions.appendRow.run({
                        tablePos: getParentTable()?.pos,
                        rowNumber,
                        direction: 'after',
                    }),
                    iconStart: _jsx(Icon, { data: ArrowDown }),
                    disabled: !actions.appendRow.isEnable({
                        tablePos: getParentTable()?.pos,
                        rowNumber,
                        direction: 'after',
                    }),
                },
                {
                    text: i18n('row.remove'),
                    action: () => actions.deleteRow.run({
                        rowNumber,
                        tablePos: getParentTable()?.pos,
                    }),
                    iconStart: _jsx(Icon, { data: Xmark }),
                    disabled: !actions.deleteRow.isEnable({
                        rowNumber,
                        tablePos: getParentTable()?.pos,
                    }),
                },
                {
                    theme: 'danger',
                    text: i18n('table.remove'),
                    action: () => actions.deleteTable.run({
                        tablePos: getParentTable()?.pos,
                        tableNode: getParentTable()?.node,
                    }),
                    iconStart: _jsx(Icon, { data: TrashBin }),
                    disabled: !actions.deleteTable.isEnable({
                        tablePos: getParentTable()?.pos,
                        tableNode: getParentTable()?.node,
                    }),
                },
            ] }, 1));
    }
    if (isInFirstRow) {
        controls.push(_jsx(DropdownMenu, { switcherWrapperClassName: b('upper-button'), renderSwitcher: (props) => (_jsx(Button, { view: 'outlined', size: 's', ...props, children: _jsx(Icon, { data: EllipsisVertical }) })), items: [
                {
                    text: i18n('column.add.before'),
                    action: () => actions.appendColumn.run({
                        tablePos: getParentTable()?.pos,
                        columnNumber,
                        direction: 'before',
                    }),
                    iconStart: _jsx(Icon, { data: ArrowLeft }),
                    disabled: !actions.appendColumn.isEnable({
                        tablePos: getParentTable()?.pos,
                        columnNumber,
                        direction: 'before',
                    }),
                },
                {
                    text: i18n('column.add.after'),
                    action: () => actions.appendColumn.run({
                        tablePos: getParentTable()?.pos,
                        columnNumber,
                        direction: 'after',
                    }),
                    iconStart: _jsx(Icon, { data: ArrowRight }),
                    disabled: !actions.appendColumn.isEnable({
                        tablePos: getParentTable()?.pos,
                        columnNumber,
                        direction: 'after',
                    }),
                },
                {
                    text: i18n('column.remove'),
                    action: () => actions.deleteColumn.run({
                        columnNumber,
                        tablePos: getParentTable()?.pos,
                    }),
                    iconStart: _jsx(Icon, { data: Xmark }),
                    disabled: !actions.deleteColumn.isEnable({
                        columnNumber,
                        tablePos: getParentTable()?.pos,
                    }),
                },
                {
                    theme: 'danger',
                    text: i18n('table.remove'),
                    action: () => actions.deleteTable.run({
                        tablePos: getParentTable()?.pos,
                        tableNode: getParentTable()?.node,
                    }),
                    iconStart: _jsx(Icon, { data: TrashBin }),
                    disabled: !actions.deleteTable.isEnable({
                        tablePos: getParentTable()?.pos,
                        tableNode: getParentTable()?.node,
                    }),
                },
            ] }, 2));
    }
    return controls.length ? _jsx(_Fragment, { children: controls }) : null;
};
export const yfmTableCellView = (node, view, getPos) => {
    const getParentTable = () => findParentNodeClosestToPos(view.state.doc.resolve(getPos()), isTableNode);
    const parentTable = getParentTable();
    const cellCoords = parentTable ? findCellCoords(parentTable.node, node) : null;
    // @ts-expect-error
    if (!cellCoords)
        return {};
    const { cellIndex, rowIndex } = cellCoords;
    const isFirstRow = rowIndex === 0;
    const isFirstColumn = cellIndex === 0;
    if (!isFirstRow && !isFirstColumn) {
        // in this case, we don't need custom nodeView.
        // @ts-expect-error
        return {};
    }
    const dom = document.createElement('td');
    if (node.attrs[YfmTableAttr.Colspan])
        dom.setAttribute('colspan', node.attrs[YfmTableAttr.Colspan]);
    if (node.attrs[YfmTableAttr.Rowspan])
        dom.setAttribute('rowspan', node.attrs[YfmTableAttr.Rowspan]);
    if (node.attrs[YfmTableAttr.CellAlign]) {
        dom.classList.add(node.attrs[YfmTableAttr.CellAlign]);
        dom.setAttribute(YfmTableAttr.CellAlign, node.attrs[YfmTableAttr.Rowspan]);
    }
    const contentDOM = document.createElement('div');
    const control = document.createElement('span');
    control.setAttribute('style', 'width: 0; height: 0; float: left;');
    dom.setAttribute('style', 'position: relative; overflow: visible;');
    dom.appendChild(contentDOM);
    dom.appendChild(control);
    const renderItem = getReactRendererFromState(view.state).createItem('yfm-table-cell-view', () => (_jsx(Portal, { container: control, children: _jsx(ErrorLoggerBoundary, { children: _jsx(Controls, { columnNumber: cellIndex, rowNumber: rowIndex, isFirstInRow: isFirstColumn, isInFirstRow: isFirstRow, getParentTable: getParentTable, view: view }) }) })));
    return {
        dom,
        contentDOM,
        destroy() {
            renderItem.remove();
        },
        ignoreMutation(mutation) {
            return mutation.target === control || control.contains(mutation.target);
        },
        update(n) {
            const { rows: nRows, cols: nCols } = getTableDimensions(n);
            const { rows, cols } = getTableDimensions(node);
            return !(rows !== nRows || cols !== nCols);
        },
    };
};
function findCellCoords(table, cell) {
    if (!table.lastChild)
        return null;
    const rows = getChildrenOfNode(table.lastChild); // children of tBody
    for (const row of rows) {
        const node = getChildByNode(row.node, cell);
        if (node) {
            return {
                rowIndex: row.index,
                cellIndex: node.index,
            };
        }
    }
    return null;
}
//# sourceMappingURL=yfmTableCellView.js.map
