import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "@emotion/react/jsx-runtime";
import React from "react";
import { Box, Button, ButtonGroup, Center, Flex, Icon, IconButton, Popover, PopoverArrow, PopoverBody, PopoverCloseButton, PopoverContent, PopoverFooter, PopoverHeader, PopoverTrigger, Portal, Switch, Text, Tooltip, useDisclosure, } from "@chakra-ui/react";
import Scrollbars from "rc-scrollbars";
import EditorContext from "@qorebase/app-runtime/src/EditorContext";
import { ArrowLeftAlt, DockTop, DockLeft, Plus, Edit, Close, } from "@feedloop/icon";
import PropsGroup from "./PropsGroup";
import format from "@qorebase/app-runtime/src/utils/format";
import iconsList from "@qorebase/app-runtime/src/components/iconsList";
import { DragDropContext, Draggable, Droppable, } from "react-beautiful-dnd";
import { RuntimeContext } from "@qorebase/app-runtime/src/RuntimeContext";
import Tree, { mutateTree, moveItemOnTree, } from "@atlaskit/tree";
import { nanoid } from "nanoid";
import { usePageParam } from "@qorebase/app-runtime/src/hooks/usePageParam";
const NavbarDesign = ({ type }) => {
    const runtimeActions = RuntimeContext.useActions();
    const positionNav = RuntimeContext.useSelectState((state) => state.navbar.sidetop.position);
    const collapsible = RuntimeContext.useSelectState((state) => state.navbar.sidetop.collapsible);
    const pageParam = usePageParam();
    const currentPage = RuntimeContext.useSelectState((state) => state.maps.page[pageParam]);
    const buttonStyle = React.useMemo(() => ({
        fontSize: "sm",
        fontWeight: "normal",
        bg: "white",
        color: "gray.900",
        _active: {
            color: "blue.500",
            bg: "blue.50",
            border: "1px solid #0065FF",
        },
    }), []);
    return (_jsxs(Flex, Object.assign({ direction: "column", gap: "2", py: "2", color: "gray.900" }, { children: [_jsxs(Flex, Object.assign({ justifyContent: "space-between" }, { children: [_jsx(Text, { children: type === "bottom"
                            ? "Show navbar in this page"
                            : "Show side/top nav in this page" }), _jsx(Switch, { isChecked: currentPage === null || currentPage === void 0 ? void 0 : currentPage.navbar[type].show, onChange: (e) => {
                            runtimeActions.setShowNavbar({ page: currentPage === null || currentPage === void 0 ? void 0 : currentPage.id }, type, e.target.checked);
                            !e.target.checked && runtimeActions.setCollapsible(false);
                        } })] })), type === "bottom" ? (_jsxs(Flex, Object.assign({ justifyContent: "space-between" }, { children: [_jsx(Text, { children: "Show drawer in this page" }), _jsx(Switch, { isChecked: currentPage === null || currentPage === void 0 ? void 0 : currentPage.navbar.drawer.show, onChange: (e) => {
                            runtimeActions.setShowNavbar({ page: currentPage === null || currentPage === void 0 ? void 0 : currentPage.id }, "drawer", e.target.checked);
                        } })] }))) : (_jsxs(_Fragment, { children: [_jsxs(Flex, Object.assign({ justifyContent: "space-between", alignItems: "center", hidden: !(currentPage === null || currentPage === void 0 ? void 0 : currentPage.navbar.sidetop.show) }, { children: [_jsx(Text, { children: "Navbar position" }), _jsx(Box, Object.assign({ border: "1px solid #E7E7E7", borderRadius: "md", p: "1" }, { children: _jsx(ButtonGroup, Object.assign({ size: "xs" }, { children: _jsx(Center, Object.assign({ gap: "1" }, { children: ["sidebar", "topbar"].map((position) => (_jsx(IconButton, Object.assign({}, buttonStyle, { "aria-label": "header", isActive: positionNav === position, icon: position === "topbar" ? _jsx(DockTop, {}) : _jsx(DockLeft, {}), onClick: () => runtimeActions.setSideTopNavbar(position) }), position))) })) })) }))] })), positionNav === "sidebar" && (_jsxs(Flex, Object.assign({ justifyContent: "space-between", mb: "2", hidden: !(currentPage === null || currentPage === void 0 ? void 0 : currentPage.navbar.sidetop.show) }, { children: [_jsx(Text, { children: "Collapsible" }), _jsx(Switch, { isChecked: collapsible, onChange: (e) => {
                                    runtimeActions.setCollapsible(e.target.checked);
                                } })] })))] }))] })));
};
const BottomNav = ({ pages }) => {
    const editorActions = EditorContext.useActions();
    const runtimeActions = RuntimeContext.useActions();
    const navigations = RuntimeContext.useSelectState((state) => state.navbar.bottom);
    const handleDragEnd = React.useCallback((result) => {
        if (!result.destination)
            return;
        runtimeActions.swapBottomNavContent(result.source.index, result.destination.index);
    }, [runtimeActions, navigations.content]);
    return (_jsxs(Flex, Object.assign({ direction: "column", gap: "2", py: "2", color: "gray.900" }, { children: [_jsx(Text, { children: "In mobile mode, you can reorder bottom navigation by drag and dropping item below" }), _jsxs(Flex, Object.assign({ mt: "2", justifyContent: "space-between" }, { children: [_jsx(Text, { children: "Show label" }), _jsx(Switch, { isChecked: navigations.showLabel, onChange: (e) => runtimeActions.setBottomNavLabel(e.target.checked) })] })), _jsx(DragDropContext, Object.assign({ onDragEnd: handleDragEnd }, { children: _jsx(Droppable, Object.assign({ droppableId: "navigations", direction: "vertical" }, { children: (provided, snapshot) => (_jsxs(_Fragment, { children: [_jsxs(Flex, Object.assign({ direction: "column", gap: "2", p: navigations.content.length > 0 ? 2 : 0 }, provided.droppableProps, { ref: provided.innerRef }, { children: [navigations.content.map((nav, idx) => (_jsx(Draggable, Object.assign({ draggableId: nav.page + idx, index: idx }, { children: (provided, snap) => (_jsxs(Flex, Object.assign({ justifyContent: "space-between", alignItems: "center", bg: "white", pl: snap.isDragging ? 2 : 0, borderRadius: "md", ref: provided.innerRef }, provided.draggableProps, provided.dragHandleProps, { children: [_jsxs(Center, Object.assign({ gap: "2" }, { children: [_jsx(Icon, { color: "gray.500", fontSize: "12px", as: iconsList[nav.icon] }), _jsx(Text, { children: nav.label })] })), _jsx(ButtonGroup, Object.assign({ size: "xs" }, { children: _jsxs(Center, Object.assign({ gap: "1" }, { children: [_jsx(IconButton, { color: "gray.500", "aria-label": "edit", variant: "ghost", icon: _jsx(Edit, { fontSize: "14px" }), onClick: () => {
                                                                    editorActions.setRightPanel({
                                                                        type: "navbar content",
                                                                    });
                                                                    editorActions.setNavbarPanel({
                                                                        type: "bottom",
                                                                        contentId: idx,
                                                                    });
                                                                } }), _jsx(IconButton, { color: "gray.500", "aria-label": "delete", variant: "ghost", icon: _jsx(Close, { fontSize: "14px" }), onClick: () => runtimeActions.removeBottomNav(idx) })] })) }))] }))) }), nav.page + idx))), provided.placeholder] })), _jsx(Tooltip, Object.assign({ label: "Bottom nav can only show up to 5 items", placement: "left", hasArrow: true, rounded: "md", arrowSize: 8, isDisabled: navigations.content.length <= 4 ||
                                    Boolean(snapshot.draggingFromThisWith), shouldWrapChildren: true }, { children: _jsx(Button, Object.assign({ size: "sm", fontWeight: "normal", variant: "outline", leftIcon: _jsx(Plus, {}), isDisabled: navigations.content.length >= 5, _disabled: {
                                        bg: "#E7E7E7",
                                        color: "gray.500",
                                        cursor: "no-drop",
                                    }, _hover: {
                                        bg: "gray.200",
                                        _disabled: {
                                            bg: "#E7E7E7",
                                        },
                                    }, w: "full", onClick: () => runtimeActions.addBottomNav({
                                        icon: "",
                                        label: "Untitled",
                                        page: pages[0].value,
                                    }) }, { children: "New bottomnav content" })) }))] })) })) }))] })));
};
const RenderItem = ({ item, provided, snapshot, isOpenWarning, destinationId, onCloseWarning, onCollapse, onExpand, removeSidetopNav, setRightPanel, setNavbarPanel, }) => {
    return (_jsxs(Popover, Object.assign({ isOpen: isOpenWarning && destinationId === item.id, placement: "left", autoFocus: true, closeOnBlur: true }, { children: [_jsxs(Flex, Object.assign({ ref: provided.innerRef }, provided.draggableProps, provided.dragHandleProps, { justifyContent: "space-between", alignItems: "center", borderRadius: "md", py: "1", pl: snapshot.isDragging || snapshot.combineTargetFor ? 2 : 0, bgColor: snapshot.combineTargetFor ? "gray.100" : "white" }, { children: [_jsx(PopoverTrigger, { children: _jsxs(Flex, Object.assign({ gap: "1" }, { children: [_jsx(Center, { children: item.children && item.children.length > 0 && (_jsx(Icon, { boxSize: 5, color: "gray.900", as: iconsList["ChevronDown"], onClick: () => item.isExpanded ? onCollapse(item.id) : onExpand(item.id), transition: "all 200ms ease-out", transform: `rotate(${item.isExpanded ? 0 : -90}deg)`, cursor: "pointer" })) }), _jsxs(Center, Object.assign({ gap: "2" }, { children: [_jsx(Icon, { color: "gray.500", fontSize: "12px", as: iconsList[item.data.icon] }), _jsx(Text, { children: item.data.label })] }))] })) }), _jsx(ButtonGroup, Object.assign({ size: "xs" }, { children: _jsxs(Center, Object.assign({ gap: "1" }, { children: [_jsx(IconButton, { color: "gray.500", "aria-label": "edit", variant: "ghost", icon: _jsx(Edit, { fontSize: "14px" }), onClick: () => {
                                        setRightPanel({
                                            type: "navbar content",
                                        });
                                        setNavbarPanel({
                                            type: "sidetop",
                                            contentId: item.id,
                                        });
                                    } }), _jsx(IconButton, { color: "gray.500", "aria-label": "delete", variant: "ghost", icon: _jsx(Close, { fontSize: "14px" }), onClick: () => {
                                        removeSidetopNav(item);
                                    } })] })) }))] })), _jsx(Portal, { children: _jsxs(PopoverContent, Object.assign({ shadow: "md" }, { children: [_jsx(PopoverHeader, Object.assign({ fontWeight: "semibold" }, { children: "Navigation item is too deep" })), _jsx(PopoverArrow, {}), _jsx(PopoverCloseButton, { onClick: onCloseWarning }), _jsx(PopoverBody, { children: "You can only rearrange navigation items up to 3 levels" }), _jsx(PopoverFooter, Object.assign({ display: "flex", justifyContent: "flex-end", border: "0" }, { children: _jsx(Button, Object.assign({ size: "xs", onClick: onCloseWarning, colorScheme: "messenger" }, { children: "Ok" })) }))] })) })] })));
};
const SideTopNav = ({ pages }) => {
    const { isOpen, onOpen, onClose } = useDisclosure();
    const runtimeActions = RuntimeContext.useActions();
    const editorActions = EditorContext.useActions();
    const navigations = RuntimeContext.useSelectState((state) => state.navbar.sidetop.content);
    const [dragId, setDragId] = React.useState("");
    const [destinationId, setDestinationId] = React.useState("");
    const onExpand = React.useCallback((itemId) => {
        const newTree = mutateTree(navigations, itemId, { isExpanded: true });
        runtimeActions.swapSidetopNavContent(newTree);
    }, [runtimeActions, navigations]);
    const onCollapse = React.useCallback((itemId) => {
        const newTree = mutateTree(navigations, itemId, { isExpanded: false });
        runtimeActions.swapSidetopNavContent(newTree);
    }, [runtimeActions, navigations]);
    const onDragEnd = React.useCallback((source, destination) => {
        if (!destination) {
            return;
        }
        const movedItem = navigations.items[dragId];
        let deepItem = movedItem.children.length > 0 ? 2 : 1;
        navigations.items[dragId].children.forEach((child) => {
            const hasSubchild = navigations.items[child].children.length > 0;
            if (hasSubchild) {
                deepItem = 3;
            }
        });
        if (deepItem === 3 && destination.parentId !== "root") {
            setDestinationId(destination.parentId);
            onOpen();
            return;
        }
        let destLevel = 1;
        const levelCounter = (nav) => {
            for (const key in navigations.items) {
                if (key !== "root" &&
                    navigations.items[key].children.includes(nav.id)) {
                    destLevel++;
                    levelCounter(navigations.items[key]);
                }
            }
        };
        levelCounter(navigations.items[destination.parentId]);
        if (destLevel >= 3 || (destLevel === 2 && deepItem >= 2)) {
            setDestinationId(destination.parentId);
            onOpen();
            return;
        }
        const newTree = moveItemOnTree(navigations, source, destination);
        runtimeActions.swapSidetopNavContent(newTree);
    }, [runtimeActions, navigations, dragId, destinationId]);
    return (_jsxs(Flex, Object.assign({ direction: "column", gap: "2", py: "2", color: "gray.900" }, { children: [_jsx(Text, { children: "In tablet and desktop mode, you can make submenu navigation by drag and dropping navigation item below" }), _jsx(Flex, Object.assign({ direction: "column", borderRadius: "md", p: navigations.items.root.children.length > 0 ? 2 : 0 }, { children: _jsx(Tree, { tree: navigations, renderItem: (e) => (_jsx(RenderItem, { item: e.item, isOpenWarning: isOpen, onCloseWarning: onClose, destinationId: destinationId, onCollapse: onCollapse, onExpand: onExpand, provided: e.provided, snapshot: e.snapshot, removeSidetopNav: runtimeActions.removeSidetopNav, setNavbarPanel: editorActions.setNavbarPanel, setRightPanel: editorActions.setRightPanel })), onDragEnd: onDragEnd, onDragStart: (e) => {
                        setDragId(e);
                    }, offsetPerLevel: 20, isDragEnabled: true, isNestingEnabled: true }) })), _jsx(Button, Object.assign({ size: "sm", fontWeight: "normal", variant: "outline", leftIcon: _jsx(Plus, {}), w: "full", onClick: () => {
                    runtimeActions.addSidetopNav({
                        id: nanoid(3),
                        children: [],
                        hasChildren: false,
                        isExpanded: false,
                        isChildrenLoading: false,
                        data: {
                            label: "Untitled",
                            icon: "",
                            page: pages[0].value,
                            linked: true,
                        },
                    });
                } }, { children: "New navigation content" }))] })));
};
const NavbarPanel = () => {
    const editorActions = EditorContext.useActions();
    const { type } = EditorContext.useSelectState((state) => state.navbarPanel);
    const pagesMap = RuntimeContext.useSelectState((state) => state.maps.page);
    const pages = React.useMemo(() => Iterator.from(Object.values(pagesMap))
        .filter((page) => page.type !== "system")
        .map((filterPage) => ({
        value: filterPage.id,
        label: format(filterPage.title, {}),
    }))
        .toArray(), [pagesMap]);
    return (_jsx(Box, Object.assign({ h: "full", bg: "white", borderLeft: "1px solid", borderColor: "gray.300" }, { children: _jsxs(Scrollbars, Object.assign({ autoHide: true }, { children: [_jsxs(Flex, Object.assign({ h: "10", alignItems: "center", pl: "3", borderBottom: "1px solid", borderColor: "gray.300", color: "gray.900", fontWeight: "semibold" }, { children: [_jsx(IconButton, { fontSize: "lg", color: "gray.900", "aria-label": "Back From Nav Panel", icon: _jsx(ArrowLeftAlt, {}), variant: "link", onClick: () => {
                                editorActions.setRightPanel({ type: "page" });
                            } }), _jsx(Text, { children: type === "bottom" ? "Bottom navbar" : "Side or top navbar" })] })), _jsx(PropsGroup, Object.assign({ name: "Display" }, { children: _jsx(NavbarDesign, { type: type }) })), _jsx(PropsGroup, Object.assign({ name: "Content" }, { children: type === "bottom" ? (_jsx(BottomNav, { pages: pages })) : (_jsx(SideTopNav, { pages: pages })) }))] })) })));
};
export default NavbarPanel;
//# sourceMappingURL=NavbarPanel.js.map