import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "@emotion/react/jsx-runtime";
/* eslint-disable fp/no-let */
import { Box, Center, Divider, Flex, Icon, Input, Menu, MenuButton, MenuItem, MenuList, Portal, Text, useDisclosure, } from "@chakra-ui/react";
import { css } from "@emotion/react";
import { MoreHorizontal } from "@feedloop/icon";
import iconsList from "@qorebase/app-runtime/src/components/iconsList";
import EditorContext from "@qorebase/app-runtime/src/EditorContext";
import { usePageParam } from "@qorebase/app-runtime/src/hooks/usePageParam";
import { getComponent, isComponent, } from "@qorebase/app-runtime/src/interfaces";
import React from "react";
import { bannedComponents } from "./ComponentsManager";
import { indent } from "./PageMenuTree";
const color = "#999";
const childrenComponent = (children, results) => {
    children.forEach((child) => {
        results.push(child.id);
        child.children && childrenComponent(child.children, results);
    });
    return results.map((id) => ({ component: id }));
};
const MenuOptions = React.memo(function MenuOptions({ component, layer1, onRemoveComponent, menuDisclosure, onRemoveFromLayout, styles, handlers, }) {
    const page = usePageParam();
    const handleRemoveComponent = React.useCallback(() => {
        const components = [];
        components.push({ component: component.id });
        if (component.children) {
            const componentsWithChildren = childrenComponent(component.children, []);
            components.push(...componentsWithChildren);
        }
        onRemoveComponent(components, { page: page }, (isComponent(component, "ColumnLayout2") ||
            isComponent(component, "ColumnLayout3")) &&
            layer1
            ? {
                layoutDetail: {
                    componentsID: (layer1[component.id] || []).map((comp) => comp.id),
                },
            }
            : undefined);
    }, [layer1, component.id, page]);
    return (_jsxs(Menu, Object.assign({ placement: "right", isOpen: menuDisclosure.isOpen, onOpen: menuDisclosure.onOpen, onClose: menuDisclosure.onClose, autoSelect: false, isLazy: true }, { children: [_jsx(MenuButton, { children: _jsx(Center, Object.assign({ height: styles.row.height, mx: 2 }, { children: _jsx(Icon, { as: MoreHorizontal, fontSize: "reg" }) })) }), _jsx(Portal, { children: _jsxs(MenuList, { children: [_jsx(MenuItem, Object.assign({ onClick: handlers.edit }, { children: "Rename" })), _jsx(Divider, { my: "8px" }), !bannedComponents.has(component.componentID) &&
                            component.metadata &&
                            component.metadata.layout && (_jsx(MenuItem, Object.assign({ onClick: () => onRemoveFromLayout(component.id) }, { children: "Remove from layout" }))), _jsx(MenuItem, Object.assign({ verticalAlign: "middle", alignItems: "center", onClick: handleRemoveComponent, color: "red.500", icon: _jsx(Icon, { as: iconsList["Delete"], color: "red.500", transform: "translateY(3px)" }) }, { children: "Delete" }))] }) })] })));
});
function MaybeToggleButton({ toggle, isOpen, isFolder, isSelected, }) {
    if (isFolder) {
        const Icons = isOpen ? iconsList.ChevronDown : iconsList.ChevronRight;
        return (_jsx(Icon, { as: Icons, fontSize: "22px", stroke: isSelected ? "white" : color, "aria-label": "expand-icon", tabIndex: -1, onClick: toggle }));
    }
    else {
        return _jsx(_Fragment, {});
    }
}
export const Node = React.memo(function NodeComponent({ innerRef, data, styles, state, handlers, onRemoveComponent, onSetActiveComponent, onMoveToLayout, onRemoveFromLayout, activeComponent, components, layer1, }) {
    var _a, _b, _c, _d, _e;
    const editorActions = EditorContext.useActions();
    const ref = React.useRef();
    const menuDisclosure = useDisclosure();
    const editNameDisclosure = useDisclosure();
    const availableLayout = React.useMemo(() => {
        return components.filter((component) => isComponent(component, "ColumnLayout2") ||
            isComponent(component, "ColumnLayout3"));
    }, [components]);
    const folder = Array.isArray(data.children);
    const open = state.isOpen;
    const rightPanel = EditorContext.useSelectState(({ rightPanel }) => rightPanel);
    const isSelected = React.useMemo(() => state.isSelected ||
        menuDisclosure.isOpen ||
        (activeComponent === data.id && rightPanel.type === "component"), [
        state.isSelected,
        menuDisclosure.isOpen,
        activeComponent,
        data.id,
        rightPanel.type,
    ]);
    return (_jsx(Flex, Object.assign({ mx: 2, style: Object.assign(Object.assign({}, styles.row), { top: Number(styles.row.top) + 8 }) }, { children: _jsxs(Flex, Object.assign({ css: css `
          padding: 0 2px;
          border-radius: 4px;
          cursor: pointer;
          background-color: ${isSelected
                ? "#E6F0FF"
                : state.isHoveringOverChild
                    ? "hsla(0 0% 0% / 0.05)"
                    : "transparent"};
          &:hover {
            background-color: #eff4fb;
          }
          ${isSelected
                ? `#component-reveal-menu {
                    opacity: 1;
                  }`
                : `
                  #component-reveal-menu {
                    transition: opacity 200ms ease;
                    opacity: 0;
                  }`}
          &:hover #component-reveal-menu {
            opacity: 1;
          }
        ` }, { children: [_jsx(Flex, Object.assign({ position: "absolute" }, { children: !!Number(styles.indent.paddingLeft) &&
                        Array.from(Array(Number(styles.indent.paddingLeft) / indent).keys()).map((key) => (_jsx(Center, { borderRight: "1px solid rgba(0, 0, 0, 0.2)", width: `${indent}px`, height: styles.row.height }, key))) })), _jsx("div", Object.assign({ ref: innerRef, style: Object.assign(Object.assign({}, styles.indent), { width: "13.375rem", overflow: "hidden" }) }, { children: _jsx(Flex, Object.assign({ paddingLeft: "6px", ref: ref, width: "full" }, { children: _jsxs(Flex, Object.assign({ w: "full", height: styles.row.height, onClick: (e) => {
                                !state.isOpen && handlers.toggle(e);
                                onSetActiveComponent(data.id);
                                editorActions.setRightPanel({
                                    type: "component",
                                    id: data.id,
                                });
                            }, alignItems: "center", onDoubleClick: handlers.edit }, { children: [_jsx(MaybeToggleButton, { toggle: handlers.toggle, isOpen: open, isFolder: folder, isSelected: state.isSelected }), _jsx(Box, { width: folder ? "4px" : "2px" }), _jsx(Icon, { fontSize: "18px", color: "blue.500", as: iconsList[(_a = getComponent(data.componentID)) === null || _a === void 0 ? void 0 : _a.icon] }), _jsx(Box, { width: "6px" }), _jsx(Flex, Object.assign({ flex: "1 1 auto", alignItems: "center", justifyContent: "space-between", w: "20%" }, { children: state.isEditing || editNameDisclosure.isOpen ? (_jsx(RenameForm, Object.assign({ defaultValue: ((_b = data.metadata) === null || _b === void 0 ? void 0 : _b.name) ||
                                            ((_c = getComponent(data.componentID)) === null || _c === void 0 ? void 0 : _c.name) ||
                                            data.componentID, styles: styles }, handlers))) : (_jsx(Text, Object.assign({ color: state.isSelected ? "#004DC4" : "#001E4D", onDoubleClick: (e) => {
                                            e.stopPropagation();
                                            // @ts-ignore
                                            handlers.edit(e);
                                            return false;
                                        }, whiteSpace: "nowrap", textOverflow: "ellipsis", overflow: "hidden" }, { children: ((_d = data.metadata) === null || _d === void 0 ? void 0 : _d.name) ||
                                            ((_e = getComponent(data.componentID)) === null || _e === void 0 ? void 0 : _e.name) ||
                                            data.componentID }))) })), data.id !== "login_component" && (_jsxs(Center, Object.assign({ onClick: (e) => e.stopPropagation() }, { children: [!!data.metadata && !!data.metadata.layout && (_jsxs(Text, { children: ["Col-", data.metadata.layout.column] })), _jsx("div", Object.assign({ id: "component-reveal-menu", css: css `
                      height: ${styles.row.height};
                    ` }, { children: _jsx(MenuOptions, { component: data, handlers: handlers, onRemoveComponent: onRemoveComponent, onMoveToLayout: onMoveToLayout, onRemoveFromLayout: onRemoveFromLayout, menuDisclosure: menuDisclosure, activeComponent: activeComponent, availableLayout: availableLayout, layer1: layer1, styles: styles }) }))] })))] })) })) }))] })) })));
});
function RenameForm({ defaultValue, submit, reset, styles }) {
    const inputProps = {
        defaultValue,
        autoFocus: true,
        onBlur: (e) => {
            submit(e.currentTarget.value);
        },
        onKeyDown: (e) => {
            switch (e.key) {
                case "Enter":
                    submit(e.currentTarget.value);
                    break;
                case "Escape":
                    reset();
                    break;
            }
        },
    };
    return (_jsx(Input, Object.assign({}, inputProps, { size: "sm", height: Number(styles.row.height) - 2, border: "transparent", paddingInline: "0", background: "white" })));
}
//# sourceMappingURL=PageTreeItem.js.map