import { __awaiter } from 'tslib';
import { jsx, jsxs, Fragment } from '@emotion/react/jsx-runtime';
import { Text, MenuButton, Button, Grid, GridItem, HStack, Box, Menu, MenuList, Input, MenuItem, Flex, Portal, Checkbox } from '@chakra-ui/react';
import { FormSubmitHookContext, useDisableCondition, defineComponent, RuntimeContext as RuntimeContext$1, VariablesProvider, useEvaluateObject, useVariablesContext } from '@qorebase/app-component';
import React from 'react';
import { ChevronDown, ChevronCheck } from '@feedloop/icon';
import useSWR from 'swr';
import produce$1, { enablePatches, produce, applyPatches } from 'immer';
import { nanoid } from 'nanoid';
import { createContext as createContext$1, useContext, useContextSelector } from 'use-context-selector';
import { v4 } from 'uuid';
import { useParams } from 'react-router-dom';
import memoize from 'fast-memoize';

const getRequiredParams = (table) => (table &&
    (("query" in table &&
        ("params" in table ? [] : table.query.paramsRequired)) ||
        ("insight" in table && table.params))) ||
    [];
const generateQueryParams = (params) => {
    const newParams = {};
    Object.keys(params).forEach((param) => {
        newParams[param] = Object.assign(Object.assign({}, params[param]), { name: param });
    });
    return newParams;
};
const getRegisteredParams = (table) => (table &&
    (("query" in table &&
        ("params" in table ? table.params : table.query.registeredParams)) ||
        ("insight" in table && table.registeredParams))) ||
    {};
const tableParams = (table) => getRequiredParams(table)
    .map((param) => ({ name: param, type: "" }))
    .concat(Object.values(table && "query" in table && "params" in table
    ? generateQueryParams(getRegisteredParams(table))
    : getRegisteredParams(table)));

const useFormSubmitHook = (listener, dependencies) => {
    const submitHookContext = React.useContext(FormSubmitHookContext);
    React.useEffect(() => {
        submitHookContext.addListener(listener);
        return () => void submitHookContext.removeListener(listener);
    }, [submitHookContext, ...dependencies]);
};

enablePatches();
function createContext(initialState, createActions, options = {}) {
    const Context = createContext$1({
        state: initialState,
        // eslint-disable-next-line @typescript-eslint/no-unused-vars -- for type inference
        setState: (modifier) => { },
        hasUndo: false,
        hasRedo: false,
        undo: () => { },
        redo: () => { },
        clearStack: () => { },
        // eslint-disable-next-line @typescript-eslint/no-unused-vars -- for type inference
        batchActions: (callback) => { },
        isDirty: false,
        clean: () => { },
    });
    const useContext$1 = () => useContext(Context);
    function useSelectState(selector) {
        return useContextSelector(Context, ({ state }) => selector(state));
    }
    const useActions = () => {
        const setState = useContextSelector(Context, ({ setState }) => setState);
        return React.useMemo(() => createActions(setState), [setState]);
    };
    const useHistory = () => useContextSelector(Context, ({ hasUndo, hasRedo, undo, redo, clearStack }) => ({
        hasUndo,
        hasRedo,
        undo,
        redo,
        clear: clearStack,
    }));
    const useBatchActions = () => useContextSelector(Context, ({ batchActions }) => batchActions);
    const useDirty = () => useContextSelector(Context, ({ isDirty, clean }) => ({ isDirty, clean }));
    const Provider = (props) => {
        var _a;
        const [state, setState] = React.useState((_a = props.value) !== null && _a !== void 0 ? _a : initialState);
        const [stack, setStack] = React.useState({
            undos: [],
            redos: [],
            batchIndex: null,
        });
        const [isDirty, setDirty] = React.useState(false);
        const setImmerState = React.useCallback((modifier, track = true) => {
            setState((state) => produce(state, modifier, (patches, inversePatches) => {
                if (patches.length === 0)
                    return;
                if (options.trackPaths &&
                    !options.trackPaths.some((trackPath) => patches.every((patch) => patch.path.join(".").startsWith(trackPath))))
                    return;
                if (track && options.trackChanges) {
                    setDirty(true);
                }
                if (options.enableHistory) {
                    setStack((stack) => {
                        return Object.assign(Object.assign({}, stack), { undos: stack.undos.concat({
                                patches,
                                inversePatches,
                            }), redos: [] });
                    });
                }
            }));
        }, []);
        const hasUndo = stack.undos.length > 0;
        const hasRedo = stack.redos.length > 0;
        const undo = React.useCallback(() => setStack((stack) => {
            const patchGroup = stack.undos.pop();
            if (!patchGroup)
                return stack;
            setState((state) => applyPatches(state, patchGroup.inversePatches));
            return Object.assign(Object.assign({}, stack), { redos: stack.redos.concat(patchGroup) });
        }), []);
        const redo = React.useCallback(() => setStack((stack) => {
            const patchGroup = stack.redos.pop();
            if (!patchGroup)
                return stack;
            setState((state) => applyPatches(state, patchGroup.patches));
            return Object.assign(Object.assign({}, stack), { undos: stack.undos.concat(patchGroup) });
        }), []);
        const batchActions = React.useCallback((callback) => {
            setStack((stack) => (Object.assign(Object.assign({}, stack), { batchIndex: stack.undos.length })));
            callback();
        }, []);
        React.useEffect(() => {
            const { undos, batchIndex } = stack;
            if (batchIndex === null)
                return;
            const batchPatchGroup = undos.slice(batchIndex).reduce((patchGroup, { patches, inversePatches }) => ({
                patches: patchGroup.patches.concat(patches),
                inversePatches: inversePatches.concat(patchGroup.inversePatches),
            }), {
                patches: [],
                inversePatches: [],
            });
            setStack({
                undos: undos.slice(0, batchIndex).concat(batchPatchGroup),
                redos: [],
                batchIndex: null,
            });
        }, [stack.batchIndex]);
        const clearStack = React.useCallback(() => setStack({ undos: [], redos: [], batchIndex: null }), []);
        const clean = React.useCallback(() => setDirty(false), []);
        const value = React.useMemo(() => ({
            state,
            setState: setImmerState,
            hasUndo,
            hasRedo,
            undo,
            redo,
            clearStack,
            batchActions,
            isDirty,
            clean,
        }), [state, setImmerState, stack, hasUndo, hasRedo]);
        return jsx(Context.Provider, Object.assign({ value: value }, { children: props.children }));
    };
    return {
        useContext: useContext$1,
        useSelectState,
        useActions,
        useHistory,
        useBatchActions,
        useDirty,
        Provider,
    };
}

const initialSchema = {
    tables: [],
    views: [],
    insights: [],
    queries: [],
};
const initialPage = {
    components: [],
    id: nanoid(3),
    properties: {
        values: {
            title: "New page",
            onOpen: [{ type: "none" }],
            onScrollToBottom: [{ type: "none" }],
            headerStyle: "default",
            action: [{ type: "none" }],
            icon: "none",
            refreshInterval: 0,
            onSuccess: [{ type: "none" }],
        },
        deletableForm: false,
    },
    title: "Untitled page",
    defaultRow: {
        type: "row-id",
        rowId: "",
    },
    staticId: false,
    navbar: {
        bottom: {
            show: true,
        },
        sidetop: {
            show: true,
        },
        drawer: {
            show: true,
        },
    },
};
const initialApp = {
    name: "Application",
    description: "",
    icon: "",
    theme_color: "#049fdc",
    config: {
        projectID: "unknown",
        appID: "",
        endpoint: "",
        id: v4(),
        initialPage: {
            entryPage: "",
            loggedInPage: "",
        },
    },
    integrations: {},
    maps: {
        component: {
            login_component: {
                id: "login_component",
                componentID: "Login",
                options: {},
                properties: {},
                showCondition: { type: "all", conditions: [] },
                disableCondition: { type: "all", conditions: [] },
                source: {
                    type: "list",
                    params: {},
                    sorts: {},
                },
                metadata: {},
            },
            register_text_input: {
                componentID: "Text Input",
                options: {},
                showCondition: { type: "all", conditions: [] },
                disableCondition: { type: "all", conditions: [] },
                id: "register_text_input",
                properties: {
                    label: "Email",
                    placeholder: "Enter your email here",
                    hidden: false,
                    defaultValue: "",
                    data: {
                        inputID: "external_id",
                        field: {
                            type: "string",
                            options: {
                                format: "text",
                            },
                        },
                        validation: {
                            required: false,
                        },
                        type: "field",
                    },
                },
                source: {
                    type: "record",
                    params: {},
                    rowId: null,
                    defaultRow: { type: "first-row" },
                },
                metadata: {},
            },
            register_password_input: {
                componentID: "Password",
                options: {},
                showCondition: { type: "all", conditions: [] },
                disableCondition: { type: "all", conditions: [] },
                id: "register_password_input",
                properties: {
                    title: "Password",
                    placeholder: "Enter your password here",
                    confirmPassword: true,
                    confirmTitle: "Confirm Password",
                    confirmPlaceholder: "Reenter your password here",
                    data: {
                        inputID: "password",
                        field: {
                            type: "string",
                            options: {
                                format: "text",
                            },
                        },
                        validation: {
                            required: true,
                        },
                        type: "field",
                    },
                },
                source: {
                    type: "record",
                    params: {},
                    rowId: null,
                    defaultRow: { type: "first-row" },
                },
                metadata: {},
            },
            register_role_input: {
                componentID: "Role",
                options: {},
                showCondition: { type: "all", conditions: [] },
                disableCondition: { type: "all", conditions: [] },
                id: "register_role_input",
                properties: {
                    roleId: "",
                },
                source: {
                    type: "record",
                    params: {},
                    rowId: null,
                    defaultRow: { type: "first-row" },
                },
                metadata: {},
            },
            forbidden_component: {
                id: "forbidden_component",
                componentID: "Forbidden",
                options: {},
                showCondition: { type: "all", conditions: [] },
                disableCondition: { type: "all", conditions: [] },
                properties: {},
                metadata: {},
                source: {
                    type: "record",
                    params: {},
                    rowId: null,
                    defaultRow: { type: "first-row" },
                },
            },
        },
        page: {
            login: Object.assign(Object.assign({}, initialPage), { id: "login", components: [{ component: "login_component" }], type: "system", title: "Login" }),
            register: Object.assign(Object.assign({}, initialPage), { id: "register", components: [
                    {
                        component: "register_text_input",
                    },
                    {
                        component: "register_password_input",
                    },
                    {
                        component: "register_role_input",
                    },
                ], type: "system", title: "Register", sourceID: "users", mode: "form" }),
            forbidden: Object.assign(Object.assign({}, initialPage), { id: "forbidden", components: [{ component: "forbidden_component" }], type: "system", title: "Forbidden" }),
        },
    },
    theme: {
        id: "Light",
        options: { primaryColor: "#1890ff" },
        navigationLayout: "sidebar",
        fonts: {
            heading: ["Inter", ""],
            body: ["Inter", ""],
        },
    },
    navbar: {
        bottom: {
            showLabel: true,
            content: [],
        },
        sidetop: {
            position: "sidebar",
            collapsible: false,
            content: {
                rootId: "root",
                items: {
                    root: {
                        id: "root",
                        children: [],
                        hasChildren: true,
                        isExpanded: true,
                        isChildrenLoading: false,
                        data: {
                            label: "root tree",
                            icon: "",
                            page: "",
                            linked: true,
                        },
                    },
                },
            },
        },
    },
    schema: initialSchema,
    customSources: {},
    components: [],
};

const regex$1 = /@\[[^*]+?]\(([^*]+?)\)/gim;
const filtrexToFormula = (filtrexString) => {
    const formulaInnerString = filtrexString.replaceAll(regex$1, (match, id) => `{{${id}}}`);
    return formulaInnerString.startsWith("=")
        ? `Filtrex(${JSON.stringify(formulaInnerString.slice(1))})`
        : `"${formulaInnerString}"`;
};
const showConditionToConditionGroup = (condition) => Array.isArray(condition)
    ? {
        type: "all",
        conditions: condition.map((condition) => ({
            id: nanoid(),
            formula: `(${filtrexToFormula(condition.value)}) == (${filtrexToFormula(condition.equals)})`,
        })),
    }
    : condition;

const objectMap = (obj, fn) => Object.fromEntries(Object.entries(obj).map(([key, val]) => [key, fn(val)]));

const normalizeAppPage = (page) => {
    var _a;
    const newPage = Object.assign(Object.assign(Object.assign({}, initialPage), page), { params: page.params || {
            rowId: ((_a = page.defaultRow) === null || _a === void 0 ? void 0 : _a.type) === "row-id" ? page.defaultRow.rowId : "",
        }, navbar: page.navbar || initialPage.navbar });
    if (["navigation", "menu"].includes(newPage.type)) {
        delete newPage.type;
    }
    return newPage;
};
const normalizeAppComponent = (component) => {
    return Object.assign(Object.assign({}, component), { showCondition: Array.isArray(component.showCondition)
            ? showConditionToConditionGroup(component.showCondition)
            : component.showCondition });
};
const normalizeApp = (app) => {
    const pages = objectMap(app.maps.page, (page) => page && normalizeAppPage(page));
    const components = objectMap(app.maps.component, (component) => normalizeAppComponent(component));
    const convertOldNav = () => {
        const pages = Object.values(app.maps.page).filter((page) => page.type !== "system");
        const bottomContent = pages.slice(0, 4).map((page) => ({
            icon: page.icon,
            label: page.title,
            page: page.id,
        }));
        const sidetopContent = pages.reduce((sidetopContent, page) => {
            if (page.type === "navigation" || page.type === "menu") {
                const { id, title, icon } = page;
                const sidetopId = nanoid(3);
                return Object.assign(Object.assign({}, sidetopContent), { root: [...sidetopContent.root, sidetopId], items: Object.assign(Object.assign({}, sidetopContent.items), { [sidetopId]: {
                            id: sidetopId,
                            children: [],
                            hasChildren: false,
                            isExpanded: false,
                            isChildrenLoading: false,
                            data: {
                                label: title,
                                icon: icon,
                                page: id,
                                linked: true,
                            },
                        } }) });
            }
            return sidetopContent;
        }, {
            items: {},
            root: [],
        });
        return {
            bottom: Object.assign(Object.assign({}, initialApp.navbar.bottom), { content: bottomContent }),
            sidetop: Object.assign(Object.assign({}, initialApp.navbar.sidetop), { content: Object.assign(Object.assign({}, initialApp.navbar.sidetop.content), { rootId: "root", items: Object.assign(Object.assign(Object.assign({}, initialApp.navbar.sidetop.content.items), sidetopContent.items), { root: Object.assign(Object.assign({}, initialApp.navbar.sidetop.content.items.root), { children: sidetopContent.root }) }) }) }),
        };
    };
    return Object.assign(Object.assign({}, app), { maps: {
            page: pages,
            component: components,
        }, integrations: app.integrations || {}, customSources: app.customSources || {}, theme: Object.assign(Object.assign({}, initialApp.theme), app.theme), navbar: app.navbar || convertOldNav(), schema: Object.assign(Object.assign({}, initialApp.schema), app.schema), components: app.components || initialApp.components });
};

/* eslint-disable fp/no-delete -- immer */
const RuntimeContext = createContext(initialApp, (modify) => {
    try {
        return {
            setTheme: (theme) => {
                modify((draft) => {
                    draft.theme = theme;
                });
            },
            setApp: (app) => {
                modify(() => {
                    return normalizeApp(app);
                });
            },
            setIcon: (url) => {
                modify((draft) => {
                    draft.icon = url;
                }, false);
            },
            setInitialPage: (entryPage) => {
                modify((draft) => {
                    draft.config.initialPage = Object.assign(Object.assign({}, draft.config.initialPage), { entryPage });
                }, false);
            },
            setLoggedInPage: (loggedInPage) => {
                modify((draft) => {
                    draft.config.initialPage = Object.assign(Object.assign({}, draft.config.initialPage), { loggedInPage });
                }, false);
            },
            addNpmComponent: (name, version) => {
                modify((draft) => {
                    if (draft.components.find((c) => c.name === name && c.version === version)) {
                        return;
                    }
                    draft.components.push({
                        name,
                        version,
                        enabled: true,
                    });
                });
            },
            removeNpmComponent: (name) => {
                modify((draft) => {
                    const index = draft.components.findIndex((c) => c.name === name);
                    if (index !== -1) {
                        draft.components.splice(index, 1);
                    }
                });
            },
            setVersionNpmComponent: (name, version) => {
                modify((draft) => {
                    const index = draft.components.findIndex((c) => c.name === name);
                    if (index !== -1) {
                        draft.components[index].version = version;
                    }
                });
            },
            setEnableNpmComponent: (name, enabled) => {
                modify((draft) => {
                    const index = draft.components.findIndex((c) => c.name === name);
                    if (index !== -1) {
                        draft.components[index].enabled = enabled;
                    }
                });
            },
            addPage(page) {
                modify((draft) => {
                    draft.maps.page[page.id] = page;
                });
            },
            addIntegration(integration) {
                modify((draft) => {
                    draft.integrations[integration.name] = integration;
                });
            },
            setIntegrationProperty: function (namespace, field, value) {
                modify((draft) => {
                    draft.integrations[namespace].properties.values[field] = value;
                });
            },
            removeIntegration(namespace) {
                modify((draft) => {
                    delete draft.integrations[namespace];
                });
            },
            addCustomSources(externalData) {
                modify((draft) => {
                    draft.customSources[externalData.name] = externalData;
                });
            },
            removeCustomSources(namespace) {
                modify((draft) => {
                    delete draft.customSources[namespace];
                });
            },
            addComponent(component, pageRef, pageOpt) {
                modify((draft) => {
                    draft.maps.component[component.id] = component;
                    if (pageRef && pageOpt && typeof pageOpt.idx === "number") {
                        draft.maps.page[pageRef.page].components.splice(pageOpt.idx, 0, {
                            component: component.id,
                        });
                    }
                    else if (pageRef) {
                        draft.maps.page[pageRef.page].components.push({
                            component: component.id,
                        });
                    }
                });
            },
            addPageAndComponents(page, components) {
                modify((draft) => {
                    draft.maps.page[page.id] = page;
                    components.forEach((component) => {
                        draft.maps.component[component.id] = component;
                    });
                });
            },
            swapComponent(target, sourceIndex, destinationIndex, deletionLength = 1) {
                modify((draft) => {
                    const components = draft.maps.page[target.page].components;
                    const removed = components.splice(sourceIndex, deletionLength);
                    removed && components.splice(destinationIndex, 0, ...removed);
                    draft.maps.page[target.page].components = components;
                });
            },
            moveComponents(listUpdateComponents) {
                modify((draft) => {
                    listUpdateComponents.forEach((comp) => {
                        draft.maps.component[comp.id].metadata = comp.metadata;
                    });
                });
            },
            swapPage(targetPages, sourceIndex, destinationIndex) {
                modify((draft) => {
                    const pages = Object.values(draft.maps.page).filter((page) => page.type !== targetPages[0].type);
                    const [removed] = targetPages.splice(sourceIndex, 1);
                    removed && targetPages.splice(destinationIndex, 0, removed);
                    const newPages = pages.concat(targetPages);
                    draft.maps.page = newPages.reduce((reduced, page) => (Object.assign(Object.assign({}, reduced), { [page.id]: page })), {});
                });
            },
            setComponentProperty: function (target, field, value) {
                modify((draft) => {
                    draft.maps.component[target.component].properties[field] = value;
                });
            },
            setComponentMetadata: function (target, field, value) {
                modify((draft) => {
                    if (draft.maps.component[target.component].metadata) {
                        draft.maps.component[target.component].metadata[field] = value;
                    }
                    else {
                        draft.maps.component[target.component].metadata = {
                            [field]: value,
                        };
                    }
                });
            },
            setPageProperty: function (target, field, value) {
                modify((draft) => {
                    draft.maps.page[target.page].properties.values[field] = value;
                });
            },
            removeComponent(target, from, option) {
                modify((draft) => {
                    var _a;
                    if ((_a = option === null || option === void 0 ? void 0 : option.layoutDetail) === null || _a === void 0 ? void 0 : _a.componentsID) {
                        option.layoutDetail.componentsID.forEach((compId) => {
                            if (draft.maps.component[compId].metadata) {
                                draft.maps.component[compId].metadata.layout = undefined;
                            }
                            else {
                                draft.maps.component[compId].metadata = {};
                            }
                        });
                    }
                    const children = Object.entries(draft.maps.component).filter(([, value]) => value.metadata.container === target.component);
                    const childrenKeys = children.map((item) => item[0]);
                    draft.maps.page[from.page].components = draft.maps.page[from.page].components.filter((ref) => ![...childrenKeys, target.component].includes(ref.component));
                    childrenKeys.forEach((key) => {
                        delete draft.maps.component[key];
                    });
                    delete draft.maps.component[target.component];
                });
            },
            removeComponents(target, from) {
                modify((draft) => {
                    draft.maps.page[from.page].components = draft.maps.page[from.page].components.filter((ref) => !target.find((comp) => comp.component === ref.component));
                    target.forEach(({ component }) => {
                        delete draft.maps.component[component];
                    });
                });
            },
            removePage(target) {
                modify((draft) => {
                    const page = draft.maps.page[target.page];
                    for (const component of page.components) {
                        delete draft.maps.component[component.component];
                    }
                    delete draft.maps.page[target.page];
                });
            },
            setComponentSource(target, source) {
                modify((draft) => {
                    draft.maps.component[target.component].source = source;
                });
            },
            setComponentLayoutMetadata(target, column) {
                modify((draft) => {
                    if (!draft.maps.component[target.component].metadata ||
                        !draft.maps.component[target.component].metadata.layout)
                        return;
                    draft.maps.component[target.component].metadata.layout.column =
                        column;
                });
            },
            removeComponentLayoutMetadata(target) {
                modify((draft) => {
                    if (!draft.maps.component[target.component].metadata ||
                        !draft.maps.component[target.component].metadata.layout)
                        return;
                    draft.maps.component[target.component].metadata.layout = undefined;
                });
            },
            addComponentShowCondition(target) {
                modify((draft) => {
                    if (draft.maps.component[target.component]) {
                        draft.maps.component[target.component].showCondition.conditions.push({
                            id: nanoid(),
                            formula: "true == true",
                        });
                    }
                });
            },
            addComponentDisableCondition(target) {
                modify((draft) => {
                    if (!draft.maps.component[target.component].disableCondition) {
                        draft.maps.component[target.component].disableCondition = {
                            type: "all",
                            conditions: [],
                        };
                    }
                    if (draft.maps.component[target.component]) {
                        draft.maps.component[target.component].disableCondition.conditions.push({
                            id: nanoid(),
                            formula: "true == true",
                        });
                    }
                });
            },
            updatePage(target, update) {
                modify((draft) => {
                    update(draft.maps.page[target.page]);
                });
            },
            updateComponentShowCondition(target, update) {
                modify((draft) => {
                    if (draft.maps.component[target.component]) {
                        update(draft.maps.component[target.component].showCondition);
                    }
                });
            },
            updateComponentDisableCondition(target, update) {
                modify((draft) => {
                    if (draft.maps.component[target.component]) {
                        update(draft.maps.component[target.component].disableCondition);
                    }
                });
            },
            removeComponentShowCondition(target, index) {
                modify((draft) => {
                    if (draft.maps.component[target.component]) {
                        draft.maps.component[target.component].showCondition.conditions =
                            draft.maps.component[target.component].showCondition.conditions.filter((cond, i) => i !== index);
                    }
                });
            },
            removeComponentDisableCondition(target, index) {
                modify((draft) => {
                    if (draft.maps.component[target.component]) {
                        draft.maps.component[target.component].disableCondition.conditions = draft.maps.component[target.component].disableCondition.conditions.filter((cond, i) => i !== index);
                    }
                });
            },
            setPageTitle(target, title) {
                modify((draft) => {
                    draft.maps.page[target.page].title = title;
                });
            },
            setShowNavbar(target, type, toggle) {
                modify((draft) => {
                    draft.maps.page[target.page].navbar[type].show = toggle;
                });
            },
            setSideTopNavbar(value) {
                modify((draft) => {
                    draft.navbar.sidetop.position = value;
                });
            },
            setCollapsible(value) {
                modify((draft) => {
                    draft.navbar.sidetop.collapsible = value;
                });
            },
            setBottomNavLabel(toggle) {
                modify((draft) => {
                    draft.navbar.bottom.showLabel = toggle;
                });
            },
            addBottomNav(nav) {
                modify((draft) => {
                    draft.navbar.bottom.content.push(nav);
                });
            },
            removeBottomNav(index) {
                modify((draft) => {
                    draft.navbar.bottom.content.splice(index, 1);
                });
            },
            setBottomNavContent(idx, key, value) {
                modify((draft) => {
                    draft.navbar.bottom.content[idx][key] = value;
                });
            },
            swapBottomNavContent(source, destination) {
                modify((draft) => {
                    const newNav = [...draft.navbar.bottom.content];
                    const targetNav = newNav[source];
                    newNav.splice(source, 1);
                    newNav.splice(destination, 0, targetNav);
                    draft.navbar.bottom.content = newNav;
                });
            },
            swapSidetopNavContent(newTree) {
                modify((draft) => {
                    draft.navbar.sidetop.content = newTree;
                });
            },
            addSidetopNav(newNav) {
                modify((draft) => {
                    draft.navbar.sidetop.content.items.root.children.push(newNav.id);
                    draft.navbar.sidetop.content.items[newNav.id] = newNav;
                });
            },
            setSidetopNavbarContent(navId, key, value) {
                modify((draft) => {
                    draft.navbar.sidetop.content.items[navId].data[key] = value;
                });
            },
            removeSidetopNav(nav) {
                modify((draft) => {
                    const sideTop = Object.assign({}, draft.navbar.sidetop.content.items);
                    if (nav.hasChildren) {
                        sideTop[nav.id].children.forEach((id) => {
                            if (sideTop[id].hasChildren) {
                                sideTop[id].children.forEach((subId) => delete sideTop[subId]);
                            }
                            delete sideTop[id];
                        });
                    }
                    delete sideTop[nav.id];
                    for (const key in sideTop) {
                        if (sideTop[key].children.find((e) => e === nav.id)) {
                            const idx = sideTop[key].children.findIndex((e) => e === nav.id);
                            sideTop[key].children.splice(idx, 1);
                            if (sideTop[key].children.length === 0) {
                                sideTop[key].hasChildren = false;
                                sideTop[key].isExpanded = false;
                            }
                        }
                    }
                    draft.navbar.sidetop.content.items = sideTop;
                });
            },
        };
    }
    catch (error) { }
}, { enableHistory: true, trackChanges: true, trackPaths: ["app"] });

const usePageParam = () => { var _a; return (_a = useParams().page) !== null && _a !== void 0 ? _a : ""; };

const useSourceView = () => {
    const tables = RuntimeContext.useSelectState((state) => state.schema.tables);
    const views = RuntimeContext.useSelectState((state) => state.schema.views);
    const pageParam = usePageParam();
    const page = RuntimeContext.useSelectState((state) => state.maps.page[pageParam]);
    const sourceView = React.useMemo(() => {
        return (tables.find((table) => table.name === (page === null || page === void 0 ? void 0 : page.sourceID)) ||
            views.find((view) => view.name === (page === null || page === void 0 ? void 0 : page.sourceID)));
    }, [tables, views, page]);
    return sourceView;
};

const regex = /@\[([^*]+?)]\(([^*]+?)\)/gim;
const format = (text, data, withDisplay = false) => {
    const replaced = (text !== null && text !== void 0 ? text : "")
        .toString()
        .replace(regex, function (substring, display, id) {
        const result = data[id];
        return typeof result !== "undefined" && result !== null
            ? result
            : withDisplay
                ? display
                : "";
    });
    return replaced;
};
var format$1 = memoize(format);

const InputComponentLabel = ({ title, name, isRequired, isEmpty, isLabel, }) => {
    return (jsxs(Text, Object.assign({ fontSize: "lg", pb: name === "rating" ? "1" : "2", "data-test": `${name}-input-title` }, { children: [title, !isLabel ||
                (!isRequired && !isEmpty && (jsxs(Text, Object.assign({ display: "inline", fontStyle: "italic" }, { children: [" ", "- Optional"] }))))] })));
};
var InputComponentLabel$1 = InputComponentLabel;

const MAX_DISPLAY_OPTION = 5;
const ManyToManyOption = (props) => {
    const label = props.hooks.useTemplate(props.properties.itemLabel);
    const isSelected = props.value.includes(props.item.id);
    const showOption = label.toLowerCase().startsWith(props.search.toLowerCase());
    const onChange = React.useCallback((event) => {
        event.preventDefault();
        props.onChange(isSelected
            ? props.value.filter((id) => id !== props.item.id)
            : props.value.concat(props.item.id));
    }, [props.onChange, isSelected, props.value, props.item.id]);
    return (showOption && (jsx(MenuItem, Object.assign({ onClick: onChange, backgroundColor: isSelected && "gray.100" }, { children: jsxs(Flex, { children: [jsx(Checkbox, { borderColor: "gray", isChecked: isSelected, mr: 2, onChange: onChange }), jsx(Text, { children: label || props.item.id })] }) }))));
};
const Option = (props) => {
    const label = props.hooks.useTemplate(props.properties.itemLabel);
    const isSelected = props.value === props.item.id;
    const showOption = label.toLowerCase().startsWith(props.search.toLowerCase());
    return (showOption && (jsx(MenuItem, Object.assign({ onClick: () => props.onChange(props.item.id), backgroundColor: isSelected && "gray.100" }, { children: label || props.item.id }))));
};
const MenuButtonValue = React.forwardRef(function MenuButtonValue(props, ref) {
    const label = props.hooks.useTemplate(props.properties.itemLabel);
    const placeholder = props.hooks.useEvaluate(props.properties.placeholder);
    // @ts-ignore
    const { isDisabled } = useDisableCondition(props.instance);
    return (jsx(MenuButton, Object.assign({ as: Button, style: {
            border: "1px solid rgb(226, 232, 240)",
            pointerEvents: isDisabled ? "none" : "auto",
            background: isDisabled && "#E7E7E7",
            color: isDisabled && "#A2A2A2",
        }, bgColor: "surface.900", width: "100%", ref: ref, textAlign: "left", borderRadius: "md", variant: "outline", fontWeight: "normal", _focus: { shadow: "0px" }, rightIcon: jsx(ChevronDown, {}) }, { children: jsx(Text, Object.assign({ noOfLines: 1, color: isDisabled && "#A2A2A2" }, { children: props.children || label || placeholder })) })));
});
const DropdownRelation = defineComponent({
    name: "Dropdown Relation",
    type: "none",
    icon: "SelectInput",
    group: "input",
    display: "inline",
    defaultProps: {
        label: "Dropdown Relation",
        placeholder: "Placeholder here",
        hidden: false,
        defaultValue: "",
        data: {
            inputID: "DropdownRelation",
            field: { type: "relation", options: {} },
            validation: {
                required: false,
            },
        },
        itemLabel: "",
        options: {
            target: "",
            params: {},
        },
    },
    propDefinition: {
        label: { group: "Design", type: "expression", options: {} },
        placeholder: {
            group: "Design",
            type: "expression",
            options: {},
        },
        hidden: {
            group: "Design",
            type: "boolean",
            options: { format: "boolean" },
        },
        data: {
            group: "Design",
            type: "state",
            options: {
                inputID: "DropdownRelation",
                field: { type: "relation", options: {} },
            },
        },
        defaultValue: {
            group: "Design",
            type: "expression",
            options: {},
        },
        itemLabel: { group: "Design", type: "custom", options: {} },
        options: {
            type: "custom",
            group: "Design",
            options: {},
            style: {
                width: "full-width",
            },
        },
    },
    Editor: () => __awaiter(void 0, void 0, void 0, function* () {
        return {
            itemLabel: (props) => {
                var _a;
                const inputID = (_a = props.values) === null || _a === void 0 ? void 0 : _a.data.inputID;
                const tables = RuntimeContext$1.useSelectState((state) => state.schema.tables);
                const view = useSourceView();
                const column = React.useMemo(() => view === null || view === void 0 ? void 0 : view.columns.find((column) => column.name === inputID), [view === null || view === void 0 ? void 0 : view.columns, inputID]);
                const targetTable = React.useMemo(() => tables.find((table) => table.name === (column === null || column === void 0 ? void 0 : column.references.targetTable)), [tables, inputID]);
                const items = React.useMemo(() => targetTable === null || targetTable === void 0 ? void 0 : targetTable.columns.map((field) => ({
                    display: `item.${field.name}`,
                    id: `item.${field.name}`,
                })).concat({
                    display: "item.id",
                    id: "item.id",
                }), [targetTable === null || targetTable === void 0 ? void 0 : targetTable.columns]);
                return (jsx(VariablesProvider, Object.assign({ variables: items }, { children: jsx(props.PropertyEditor.string, Object.assign({}, props)) })));
            },
            options: (props) => {
                var _a, _b, _c;
                const schema = RuntimeContext$1.useSelectState((state) => state.schema);
                const selectedColumn = React.useMemo(() => {
                    if (!!props.view && Array.isArray(props.view.columns)) {
                        return props.view.columns.find((col) => { var _a; return col.name === ((_a = props.values) === null || _a === void 0 ? void 0 : _a.data.inputID); });
                    }
                    return;
                }, [props.view, props.values]);
                const selectedSourceTable = React.useMemo(() => {
                    return schema.tables.find((t) => t.name === (selectedColumn === null || selectedColumn === void 0 ? void 0 : selectedColumn.references.targetTable));
                }, [selectedColumn, schema.tables]);
                const optionsMap = React.useMemo(() => {
                    if (!selectedSourceTable)
                        return [];
                    const views = schema.views
                        .filter((view) => view.query.table === selectedSourceTable.name)
                        .map((v) => ({
                        label: v.name,
                        value: v.name,
                    }));
                    const insights = schema.insights
                        .filter((insight) => insight.table === selectedSourceTable.name)
                        .map((v) => ({
                        label: v.name,
                        value: v.name,
                    }));
                    const table = {
                        label: selectedSourceTable.name,
                        value: selectedSourceTable.name,
                    };
                    return [table, ...views, ...insights];
                }, [schema, selectedSourceTable]);
                const [search, setSearch] = React.useState("");
                const isValidTable = React.useMemo(() => {
                    var _a;
                    return (!!selectedSourceTable &&
                        (selectedSourceTable.name === ((_a = props.value) === null || _a === void 0 ? void 0 : _a.target) ||
                            !!schema.views.find((v) => {
                                var _a;
                                return v.query.table === selectedSourceTable.name &&
                                    v.name === ((_a = props.value) === null || _a === void 0 ? void 0 : _a.target);
                            }) ||
                            !!schema.insights.find((i) => {
                                var _a;
                                return i.table === selectedSourceTable.name &&
                                    i.name === ((_a = props.value) === null || _a === void 0 ? void 0 : _a.target);
                            })));
                }, [schema, selectedSourceTable, (_a = props.value) === null || _a === void 0 ? void 0 : _a.target]);
                const handleSearchInput = React.useCallback((e) => setSearch(e.target.value), []);
                const resetSearch = React.useCallback(() => setSearch(""), []);
                const source = React.useMemo(() => {
                    var _a;
                    if (!isValidTable)
                        return;
                    if ((selectedSourceTable === null || selectedSourceTable === void 0 ? void 0 : selectedSourceTable.name) === ((_a = props.value) === null || _a === void 0 ? void 0 : _a.target)) {
                        return selectedSourceTable;
                    }
                    const view = schema.views.find((v) => { var _a; return v.name === ((_a = props.value) === null || _a === void 0 ? void 0 : _a.target); });
                    if (view)
                        return view;
                    const insight = schema.insights.find((i) => { var _a; return i.name === ((_a = props.value) === null || _a === void 0 ? void 0 : _a.target); });
                    if (insight)
                        return insight;
                    return;
                }, [schema, (_b = props.value) === null || _b === void 0 ? void 0 : _b.target, selectedSourceTable, isValidTable]);
                const params = React.useMemo(() => {
                    if (source) {
                        return (tableParams(source).map((param) => ({
                            slug: param.name,
                            type: param.type,
                            required: true,
                        })) || []);
                    }
                    return [];
                }, [source]);
                const handleUpdateParams = React.useCallback((slug, value) => {
                    props.onChange(produce$1(props.value, (draft) => {
                        if (value === "0") {
                            draft.params[slug] = "";
                        }
                        else {
                            draft.params[slug] = value;
                        }
                    }));
                }, [props.value]);
                React.useEffect(() => {
                    if (!isValidTable && !!selectedSourceTable) {
                        props.onChange({ target: selectedSourceTable.name, params: {} });
                    }
                }, [isValidTable, selectedSourceTable]);
                if (!selectedSourceTable)
                    return null;
                return (jsxs(Grid, Object.assign({ templateColumns: "repeat(12, 1fr)", py: "10px", gap: 2 }, { children: [jsx(GridItem, Object.assign({ colSpan: 3, maxW: "full", display: "flex" }, { children: jsx(HStack, Object.assign({ alignItems: "start", pt: "10px" }, { children: jsx(Text, Object.assign({ fontSize: "sm", color: "#6F809A", textTransform: "capitalize" }, { children: "Options" })) })) })), jsx(GridItem, Object.assign({ colSpan: 9, maxW: "full", alignItems: "center", justifyContent: "flex-end" }, { children: jsxs(Box, { children: [jsx(Box, { children: jsxs(Menu, Object.assign({ onClose: resetSearch, isLazy: true }, { children: [jsx(MenuButton, Object.assign({ as: Button, style: { border: "1px solid rgb(226, 232, 240)" }, bgColor: "surface.900", width: "100%", textAlign: "left", borderRadius: "md", variant: "outline", fontWeight: "normal", size: "sm", _focus: { shadow: "0px", background: "none" }, _hover: { background: "none" }, _active: { background: "none" }, rightIcon: jsx(Box, Object.assign({ bg: "white", padding: "4px", pr: "0" }, { children: jsx(ChevronDown, {}) })) }, { children: ((_c = props.value) === null || _c === void 0 ? void 0 : _c.target) || "Select options" })), jsxs(MenuList, Object.assign({ maxW: "200px" }, { children: [jsx(Box, Object.assign({ px: "8px", pb: "8px" }, { children: jsx(Input, { placeholder: "Search", onChange: handleSearchInput, value: search }) })), optionsMap.map((opt) => {
                                                            var _a, _b, _c;
                                                            return (jsx(MenuItem, Object.assign({ display: !opt.value.includes(search) && "none", onClick: () => {
                                                                    props.onChange(Object.assign(Object.assign({}, props.value), { target: opt.value || "" }));
                                                                } }, { children: jsxs(Flex, { children: [jsx(Text, Object.assign({ flex: 1, color: ((_a = props.value) === null || _a === void 0 ? void 0 : _a.target) === opt.value && "#0065FF" }, { children: opt.label })), ((_b = props.value) === null || _b === void 0 ? void 0 : _b.target) === opt.value && (jsx(ChevronCheck, { color: ((_c = props.value) === null || _c === void 0 ? void 0 : _c.target) === opt.value && "#0065FF" }))] }) }), opt.value));
                                                        })] }))] })) }), jsx(Box, Object.assign({ pt: "1rem" }, { children: params.length > 0 && (jsxs(Fragment, { children: [jsx(Text, Object.assign({ fontWeight: "semibold", fontSize: "sm", color: "#A6B0C1" }, { children: "Parameters" })), params.map((param) => {
                                                    var _a;
                                                    return (jsxs(Grid, Object.assign({ templateColumns: "repeat(12, 1fr)", gap: 2, my: "8px" }, { children: [jsx(GridItem, Object.assign({ colSpan: 3, display: "flex", alignItems: "center" }, { children: jsx(Text, Object.assign({ fontSize: "sm", color: "#6F809A" }, { children: param.slug })) })), jsx(GridItem, Object.assign({ colSpan: 9, my: "8px" }, { children: jsx(props.PropertyEditor.string, { propDef: {
                                                                        type: "string",
                                                                        options: { format: "text" },
                                                                    }, propName: param.slug, value: (_a = props.value) === null || _a === void 0 ? void 0 : _a.params[param.slug], onChange: (value) => {
                                                                        handleUpdateParams(param.slug, value);
                                                                    } }) }))] }), param.slug));
                                                })] })) }))] }) }))] })));
            },
        };
    }),
    Component: (props) => {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
        const boxWidth = React.useRef(null);
        const placeholder = props.hooks.useEvaluate(props.properties.placeholder);
        const defaultValue = props.hooks.useEvaluate(props.properties.defaultValue);
        const title = props.hooks.useEvaluate(props.properties.label);
        const params = useEvaluateObject(((_a = props.properties.options) === null || _a === void 0 ? void 0 : _a.params) || {});
        const ref = React.useRef(null);
        const data = props.hooks.useRuntimeInput(props.properties.data, props.data.page.row, {
            validate: (value) => {
                if (typeof value === "undefined") {
                    return { error: "" };
                }
                else if (!value) {
                    return { error: "Required field, Please enter the data" };
                }
            },
        });
        const [search, setSearch] = React.useState("");
        const { values } = useVariablesContext();
        React.useEffect(() => {
            const value = parseInt(defaultValue);
            data.onChange(isNaN(value) ? undefined : value);
        }, [defaultValue, data.onChange]);
        const tableName = React.useMemo(() => {
            var _a, _b;
            return ((_a = props.app.schema.tables.find((t) => t.name === props.pageSource.target)) === null || _a === void 0 ? void 0 : _a.name) ||
                ((_b = props.app.schema.views.find((v) => v.name === props.pageSource.target)) === null || _b === void 0 ? void 0 : _b.query.table);
        }, [props.app.schema, props.pageSource.target]);
        const relationData = React.useMemo(() => {
            const currentView = props.app.schema.tables.find((table) => table.name === tableName);
            const field = currentView === null || currentView === void 0 ? void 0 : currentView.columns.find((field) => field.name === props.properties.data.inputID);
            const table = field &&
                props.app.schema.tables.find((table) => table.name === field.references.targetTable);
            return { table, field };
        }, [props.app.schema, props.properties.data.inputID, tableName]);
        const isOneToMany = React.useMemo(() => {
            var _a, _b;
            return ((_a = relationData.field) === null || _a === void 0 ? void 0 : _a.references.type) === "OneToMany" &&
                !((_b = relationData.field) === null || _b === void 0 ? void 0 : _b.references.origin);
        }, [relationData]);
        const isManyToMany = React.useMemo(() => { var _a; return ((_a = relationData.field) === null || _a === void 0 ? void 0 : _a.references.type) === "ManyToMany"; }, [relationData]);
        const [selectedIds, setSelectedIds] = React.useState([]);
        const client = props.hooks.useClient();
        const fieldName = React.useMemo(() => {
            var _a, _b;
            if (isOneToMany) {
                const lastIndex = props.properties.data.inputID.lastIndexOf("_items");
                return props.properties.data.inputID.slice(0, lastIndex === -1 ? Infinity : lastIndex);
            }
            const lastIndex = props.properties.data.inputID.lastIndexOf((_a = relationData.field) === null || _a === void 0 ? void 0 : _a.references.targetTable);
            return props.properties.data.inputID
                .slice(0, lastIndex)
                .concat(tableName, props.properties.data.inputID.slice(lastIndex + (((_b = relationData.field) === null || _b === void 0 ? void 0 : _b.references.targetTable.length) || 0)));
        }, [
            props.properties.data.inputID,
            (_b = relationData.field) === null || _b === void 0 ? void 0 : _b.references.targetTable,
            tableName,
        ]);
        const options = useSWR([client, (_c = relationData.table) === null || _c === void 0 ? void 0 : _c.name, props.properties.options, params], () => __awaiter(void 0, void 0, void 0, function* () {
            var _m, _o, _p, _q, _r, _s, _t;
            const table = ((_m = relationData.table) === null || _m === void 0 ? void 0 : _m.name) === ((_o = props.properties.options) === null || _o === void 0 ? void 0 : _o.target)
                ? client.table((_p = relationData.table) === null || _p === void 0 ? void 0 : _p.name)
                : client.view((_q = props.properties.options) === null || _q === void 0 ? void 0 : _q.target);
            const data = yield table
                .readRows({ params }, {
                skip: !((_r = props.properties.options) === null || _r === void 0 ? void 0 : _r.target) || !((_s = relationData.table) === null || _s === void 0 ? void 0 : _s.name),
            })
                .toPromise();
            return ((_t = data.data) === null || _t === void 0 ? void 0 : _t.nodes) || [];
        }), {
            suspense: !!props.pageSource.prefetch,
        });
        const selectedData = useSWR([
            client,
            isManyToMany,
            isOneToMany,
            relationData.field,
            fieldName,
            (_e = (_d = props.data.page) === null || _d === void 0 ? void 0 : _d.row) === null || _e === void 0 ? void 0 : _e.id,
        ], () => {
            var _a, _b, _c, _d, _e;
            return isManyToMany || isOneToMany
                ? client
                    .table((_a = relationData.field) === null || _a === void 0 ? void 0 : _a.references.targetTable)
                    .readRows({
                    condition: {
                        [fieldName]: {
                            id: { $eq: (_c = (_b = props.data.page) === null || _b === void 0 ? void 0 : _b.row) === null || _c === void 0 ? void 0 : _c.id },
                        },
                    },
                }, {
                    skip: !((_e = (_d = props.data.page) === null || _d === void 0 ? void 0 : _d.row) === null || _e === void 0 ? void 0 : _e.id),
                })
                    .toPromise()
                    .then((data) => {
                    var _a;
                    return ((_a = data.data) === null || _a === void 0 ? void 0 : _a.nodes) || [];
                })
                : Promise.resolve([]);
        }, {
            suspense: !!props.pageSource.prefetch,
        });
        React.useEffect(() => {
            var _a;
            if (isManyToMany || isOneToMany) {
                setSelectedIds(((_a = selectedData.data) === null || _a === void 0 ? void 0 : _a.map((data) => data.id)) || []);
                return;
            }
            if (props.data.page.row[props.properties.data.inputID]) {
                data.onChange(props.data.page.row[props.properties.data.inputID]);
            }
        }, [
            (_f = props.data.page.row) === null || _f === void 0 ? void 0 : _f.id,
            selectedData.data,
            isManyToMany,
            isOneToMany,
            props.properties.data.inputID,
        ]);
        useFormSubmitHook((row) => __awaiter(void 0, void 0, void 0, function* () {
            if (!(isManyToMany || isOneToMany))
                return;
            const addRelations = selectedIds
                .filter((id) => !(selectedData.data || []).find((row) => row.id === id))
                .map((id) => ({
                operation: "AddRelation",
                instruction: {
                    table: tableName,
                    name: `addRelation_${tableName}_${props.properties.data.inputID}_${id}`,
                    relation: {
                        name: props.properties.data.inputID,
                        data: {
                            origin: row.id,
                            target: id,
                        },
                    },
                },
            }));
            const removeRelations = (selectedData.data || [])
                .map((row) => row.id)
                .filter((id) => !selectedIds.includes(id))
                .map((id) => ({
                operation: "RemoveRelation",
                instruction: {
                    table: tableName,
                    name: `removeRelation_${tableName}_${props.properties.data.inputID}_${id}`,
                    relation: {
                        name: props.properties.data.inputID,
                        data: {
                            origin: row.id,
                            target: id,
                        },
                    },
                },
            }));
            yield client.project.axios({
                baseURL: client.project.config.endpoint,
                url: "/v1/execute",
                method: "POST",
                data: {
                    operations: addRelations.concat(removeRelations),
                },
            });
        }), [
            isManyToMany,
            selectedIds,
            selectedData.data,
            tableName,
            props.properties.data.inputID,
            client,
        ]);
        const itemRow = (_g = options.data) === null || _g === void 0 ? void 0 : _g.find((row) => row.id === data.value);
        return (jsxs(Box, Object.assign({ display: props.properties.hidden ? "none" : undefined }, { children: [jsx(InputComponentLabel$1, { title: title, name: "dropdown-relation", isRequired: (_h = props.properties.data.validation) === null || _h === void 0 ? void 0 : _h.required, isEmpty: title.length === 0 }), jsx(Box, Object.assign({ ref: ref }, { children: jsx(Portal, Object.assign({ containerRef: ref }, { children: jsxs(Menu, Object.assign({ isLazy: true }, { children: [jsx(props.components.ListItemVariables, Object.assign({ variables: itemRow || {} }, { children: jsx(MenuButtonValue, Object.assign({ ref: boxWidth }, props, { children: isManyToMany || isOneToMany
                                            ? (options.data || [])
                                                .filter((row) => selectedIds.includes(row.id))
                                                .map((row) => {
                                                return format$1(props.properties.itemLabel, Object.assign(Object.assign({}, values), Object.fromEntries(Object.entries(row).map(([key, value]) => [
                                                    `item.${key}`,
                                                    value,
                                                ]))));
                                            })
                                                .join(", ")
                                            : null })) })), jsx(Portal, Object.assign({ appendToParentPortal: true }, { children: jsxs(MenuList, Object.assign({ border: "0px", width: (_j = boxWidth === null || boxWidth === void 0 ? void 0 : boxWidth.current) === null || _j === void 0 ? void 0 : _j.offsetWidth, zIndex: 3 }, { children: [jsx(Text, Object.assign({ color: "gray", py: 2, px: 4, style: { cursor: "default" } }, { children: placeholder })), ((_k = options.data) === null || _k === void 0 ? void 0 : _k.length) > MAX_DISPLAY_OPTION && (jsx(Input, { value: search, onChange: (e) => setSearch(e.target.value), placeholder: "Search...", mb: 2 })), jsx(Box, Object.assign({ maxH: MAX_DISPLAY_OPTION * 8, overflowY: "auto" }, { children: (_l = options.data) === null || _l === void 0 ? void 0 : _l.map((option) => (jsx(props.components.ListItemVariables, Object.assign({ variables: option }, { children: isManyToMany || isOneToMany ? (jsx(ManyToManyOption, Object.assign({ item: option, onChange: setSelectedIds, value: selectedIds, search: search }, props))) : (jsx(Option, Object.assign({ item: option, onChange: data.onChange, value: data.value, search: search }, props))) }), option.id))) }))] })) }))] })) })) })), !!data.validation.error && (jsx(Text, Object.assign({ fontSize: "sm", color: "red" }, { children: data.validation.error })))] })));
    },
});

export { DropdownRelation as default };
