import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
/*
This file is part of the Notesnook project (https://notesnook.com/)

Copyright (C) 2023 Streetwriters (Private) Limited

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
import { Flex } from "@theme-ui/components";
import { ReactNodeView } from "../react";
import { useEffect, useRef } from "react";
import { updateColumnsOnResize } from "@tiptap/pm/tables";
import { InsertColumnRight, InsertRowBelow, RowProperties, TableProperties } from "../../toolbar/tools/table";
import { getToolDefinition } from "../../toolbar/tool-definitions";
import { getPosition } from "@notesnook/ui";
import { findSelectedDOMNode, hasSameAttributes } from "../../utils/prosemirror";
import { DesktopOnly } from "../../components/responsive";
export function TableComponent(props) {
    const { editor, node, forwardRef } = props;
    const colgroupRef = useRef(null);
    const tableRef = useRef();
    const { textDirection } = node.attrs;
    useEffect(() => {
        if (!colgroupRef.current || !tableRef.current)
            return;
        updateColumnsOnResize(node, colgroupRef.current, tableRef.current, 50);
    }, [node]);
    return (_jsxs(_Fragment, { children: [_jsxs(DesktopOnly, { children: [_jsx(TableRowToolbar, { editor: editor, table: tableRef, textDirection: textDirection }), _jsx(TableColumnToolbar, { editor: editor, table: tableRef, textDirection: textDirection })] }), _jsx("div", { className: "tableWrapper", dir: textDirection, children: _jsx("table", { ref: (ref) => {
                        forwardRef === null || forwardRef === void 0 ? void 0 : forwardRef(ref);
                        tableRef.current = ref || undefined;
                    }, children: _jsx("colgroup", { ref: colgroupRef }) }) })] }));
}
export function TableNodeView(editor) {
    class TableNode extends ReactNodeView {
        constructor(node) {
            super(node, editor, () => 0, // todo
            {
                component: TableComponent,
                shouldUpdate: (prev, next) => {
                    return (!hasSameAttributes(prev.attrs, next.attrs) ||
                        prev.childCount !== next.childCount);
                },
                contentDOMFactory: () => {
                    const dom = document.createElement("tbody");
                    return { dom };
                },
                wrapperFactory: () => {
                    const dom = document.createElement("div");
                    dom.style.position = "relative";
                    return dom;
                }
            });
            super.init();
        }
    }
    return TableNode;
}
function TableRowToolbar(props) {
    const { editor, textDirection, table } = props;
    const rowToolsRef = useRef(null);
    useEffect(() => {
        function onSelectionUpdate() {
            if (!rowToolsRef.current || !(table === null || table === void 0 ? void 0 : table.current)) {
                return;
            }
            const currentRow = findSelectedDOMNode(editor, ["tableRow"]);
            if (!currentRow || !table.current.contains(currentRow)) {
                rowToolsRef.current.style.display = "none";
                return;
            }
            rowToolsRef.current.style.display = "flex";
            const pos = getPosition(rowToolsRef.current, {
                location: "left",
                target: currentRow,
                align: "start",
                xOffset: -5,
                yOffset: -3
            });
            rowToolsRef.current.style.top = `${pos.top}px`;
            if (textDirection) {
                rowToolsRef.current.style.right = `${pos.left}px`;
                rowToolsRef.current.style.left = `unset`;
            }
            else {
                rowToolsRef.current.style.left = `${pos.left}px`;
                rowToolsRef.current.style.right = `unset`;
            }
        }
        editor.on("selectionUpdate", onSelectionUpdate);
        return () => {
            editor.off("selectionUpdate", onSelectionUpdate);
        };
    }, [textDirection]);
    return (_jsxs(Flex, { ref: rowToolsRef, sx: {
            display: "none",
            zIndex: 999,
            top: 0,
            left: 0,
            position: "absolute",
            bg: "background",
            flexWrap: "nowrap",
            borderRadius: "default",
            flexDirection: "column",
            opacity: 0.3,
            ":hover": {
                opacity: 1
            }
        }, children: [_jsx(RowProperties, Object.assign({}, getToolDefinition("rowProperties"), { icon: "more", variant: "small", editor: editor })), _jsx(InsertRowBelow, Object.assign({}, getToolDefinition("insertRowBelow"), { editor: editor, variant: "small" }))] }));
}
function TableColumnToolbar(props) {
    const { editor, table } = props;
    const columnToolsRef = useRef(null);
    useEffect(() => {
        function onSelectionUpdate() {
            var _a;
            if (!columnToolsRef.current || !(table === null || table === void 0 ? void 0 : table.current)) {
                return;
            }
            const currentCell = findSelectedDOMNode(editor, [
                "tableCell",
                "tableHeader"
            ]);
            if (!currentCell || !table.current.contains(currentCell)) {
                columnToolsRef.current.style.display = `none`;
                return;
            }
            columnToolsRef.current.style.display = "flex";
            // tableRef.current
            const pos = getPosition(columnToolsRef.current, {
                location: "top",
                align: "center",
                target: currentCell,
                yAnchor: table.current,
                yOffset: 2
            });
            columnToolsRef.current.style.left = `${pos.left - (((_a = table.current.parentElement) === null || _a === void 0 ? void 0 : _a.scrollLeft) || 0)}px`;
            columnToolsRef.current.style.top = `${pos.top}px`;
        }
        editor.on("selectionUpdate", onSelectionUpdate);
        return () => {
            editor.off("selectionUpdate", onSelectionUpdate);
        };
    }, []);
    return (_jsxs(Flex, { ref: columnToolsRef, sx: {
            display: "none",
            zIndex: 999,
            top: 0,
            left: 0,
            position: "absolute",
            bg: "background",
            flexWrap: "nowrap",
            borderRadius: "default",
            opacity: 0.3,
            ":hover": {
                opacity: 1
            }
        }, children: [_jsx(TableProperties, { editor: editor, title: "Table properties", icon: "more", variant: "small" }), _jsx(InsertColumnRight, Object.assign({}, getToolDefinition("insertColumnRight"), { editor: editor, variant: "small", icon: "plus" }))] }));
}
