import { __awaiter } from "tslib";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "@emotion/react/jsx-runtime";
/* eslint-disable fp/no-let */
import React from "react";
import { nanoid } from "nanoid";
import StringPropertyEditor from "./string";
import { RuntimeContext } from "@qorebase/app-runtime/src/RuntimeContext";
import format from "@qorebase/app-runtime/src/utils/format";
import { buildComponent, } from "@qorebase/app-runtime/src/interfaces";
import { Text, VStack, Box, Select, Grid, GridItem, Tooltip, Flex, Button, Spacer, Switch, Stack, Icon, useDisclosure, HStack, IconButton, MenuButton, Menu, MenuItem, MenuList, Center, Drawer, DrawerBody, DrawerContent, Portal, FormLabel, SimpleGrid, } from "@chakra-ui/react";
import produce from "immer";
import { ToastEditorModal, ToastNotificationComponent, } from "@qorebase/app-runtime/src/ToastNotification";
import PayloadEditor from "../PayloadEditor";
import qoreStorageClient from "../../hooks/qoreStorageClient";
import useSWRImmutable from "swr/immutable";
import iconsList from "@qorebase/app-runtime/src/components/iconsList";
import { ActionText, ArrowLeft, CommentDetail, ChevronDown, Lightning, Plus, Scan, Close, Information, Link, Login, LogOut, NoEntry, Redo, Sitemap, Drag, OpenModal, CloseModal, Loader, Analyse, } from "@feedloop/icon";
import { Input, Textarea } from "@feedloop/uikit";
import { css } from "@emotion/react";
import _, { camelCase } from "lodash";
import PropsGroup from "../PropsGroup";
import Scrollbars from "rc-scrollbars";
import { DragDropContext, Draggable, Droppable, } from "react-beautiful-dnd";
import { useDebounce } from "use-debounce";
import ExpressionPropertyEditor from "./expression";
import { useVariablesContext, VariablesProvider, } from "@qorebase/app-runtime/src/VariablesContext";
import { humanize } from "@qorebase/app-runtime/src/utils/humanizeString";
import { useSourceView } from "../../hooks/useSourceView";
import { useViewFieldsVariables } from "../../hooks/useViewFieldsVariables";
import { initialPage } from "@qorebase/app-runtime/src/InitialData";
import { usePageParam } from "@qorebase/app-runtime/src/hooks/usePageParam";
const actionDrawerStyle = {
    paddingInline: "unset",
    borderBottom: "0px",
    paddingBottom: "16px",
};
const motionType = [
    "None",
    "Fade",
    "Slide Up",
    "Slide Down",
    "Slide Left",
    "Slide Right",
    "Scale",
];
const modalMotionType = ["None", "Slide In Right", "Slide In Bottom", "Scale"];
const ActionPropertyBuildersMap = {
    none: {
        component: () => null,
        icon: NoEntry,
    },
    login: {
        component: (props) => {
            return (_jsxs(PropsGroup, Object.assign({ name: "Login", style: actionDrawerStyle }, { children: [_jsxs(Box, { children: [_jsx(GridItem, Object.assign({ colSpan: 3, maxW: "full", display: "flex" }, { children: _jsx(HStack, { children: _jsx(FormLabel, { children: "Username" }) }) })), _jsx(StringPropertyEditor, { propDef: {
                                    type: "string",
                                    options: { format: "text" },
                                }, propName: "Username", value: props.action.username, onChange: (username) => {
                                    props.onChange(Object.assign(Object.assign({}, props.action), { username }));
                                } })] }), _jsxs(Box, { children: [_jsx(GridItem, Object.assign({ colSpan: 3, maxW: "full", display: "flex" }, { children: _jsx(HStack, { children: _jsx(FormLabel, { children: "Password" }) }) })), _jsx(StringPropertyEditor, { propDef: {
                                    type: "string",
                                    options: { format: "text" },
                                }, propName: "Password", value: props.action.password, onChange: (password) => {
                                    props.onChange(Object.assign(Object.assign({}, props.action), { password }));
                                } })] })] })));
        },
        icon: Login,
    },
    logout: {
        component: () => null,
        icon: LogOut,
    },
    back_to_login: {
        component: () => null,
        icon: Login,
    },
    refresh_data: {
        component: () => null,
        icon: Analyse,
    },
    view_detail: {
        component: () => {
            return null;
        },
        icon: CommentDetail,
    },
    open_link: {
        component: (props) => {
            return (_jsx(PropsGroup, Object.assign({ name: "Direct link", style: actionDrawerStyle }, { children: _jsx(Box, { children: _jsx(StringPropertyEditor, { propDef: {
                            type: "string",
                            options: { format: "text" },
                        }, propName: "Link", value: props.action.link, onChange: (link) => {
                            props.onChange(Object.assign(Object.assign({}, props.action), { link }));
                        } }) }) })));
        },
        icon: Link,
    },
    trigger_action: {
        icon: ActionText,
        provides: ["response.statusCode", "response.message"],
        component: (props) => {
            var _a, _b;
            const currentView = useSourceView();
            const fieldsVariables = useViewFieldsVariables(currentView, (field) => field.type === "action");
            const [action, setAction] = React.useState(Object.assign(Object.assign({}, actionTypeDefaultValues.trigger_action), props.action));
            const [stateAction] = useDebounce(action, 300);
            React.useEffect(() => {
                props.onChange(stateAction);
            }, [stateAction]);
            const [actionModal, setActionModal] = React.useState(null);
            const handleChange = React.useCallback((actionName) => {
                setAction((action) => produce(action, (draft) => {
                    draft.actionName = actionName;
                }));
            }, [currentView]);
            const handleEventNameChange = React.useCallback((eventName) => {
                setAction((action) => produce(action, (draft) => {
                    draft.eventName = eventName;
                }));
            }, []);
            const handleSavePayload = React.useCallback((payload) => {
                setAction((action) => produce(action, (draft) => {
                    draft.payload = payload;
                }));
            }, []);
            const OnSuccessActionProperty = React.useMemo(() => { var _a; return ActionPropertyBuildersMap[((_a = action.onSuccess) === null || _a === void 0 ? void 0 : _a.type) || "none"].component; }, [action.onSuccess, ActionPropertyBuildersMap]);
            const OnFailActionProperty = React.useMemo(() => { var _a; return ActionPropertyBuildersMap[((_a = action.onFail) === null || _a === void 0 ? void 0 : _a.type) || "none"].component; }, [action.onFail, ActionPropertyBuildersMap]);
            const onChangePostActionTypeHandlers = React.useMemo(() => {
                const onChangePostActionType = (type) => (e) => setAction((action) => produce(action, (draft) => {
                    draft[type] =
                        actionTypeDefaultValues[e.target.value];
                }));
                return {
                    onSuccess: onChangePostActionType("onSuccess"),
                    onFail: onChangePostActionType("onFail"),
                };
            }, [action]);
            const onSavePostActionHandlers = React.useMemo(() => {
                const onSavePostAction = (type) => (postAction) => {
                    setAction((action) => produce(action, (draft) => {
                        draft[type] = postAction;
                    }));
                };
                return {
                    onSuccess: onSavePostAction("onSuccess"),
                    onFail: onSavePostAction("onFail"),
                };
            }, [action]);
            const onToggleNotification = React.useCallback((event) => {
                setAction((action) => produce(action, (draft) => {
                    draft.showNotification = event.currentTarget.checked;
                }));
            }, []);
            const onSaveMessageHandlers = React.useMemo(() => {
                const onSaveMessage = (type) => (value) => {
                    setAction((action) => produce(action, (draft) => {
                        draft.notification[type] = value;
                    }));
                };
                return {
                    onSuccess: onSaveMessage("onSuccess"),
                    onFail: onSaveMessage("onFail"),
                };
            }, [action]);
            React.useEffect(() => {
                var _a;
                (_a = props.handleModalDisclosure) === null || _a === void 0 ? void 0 : _a.call(props, !!actionModal);
            }, [actionModal]);
            return (_jsx(PropsGroup, Object.assign({ name: "Trigger", style: actionDrawerStyle }, { children: _jsxs(VStack, Object.assign({ width: "100%" }, { children: [actionModal === "payload" && (_jsx(PayloadEditor, { onClose: () => setActionModal(null), onSave: handleSavePayload, defaultPayload: action.payload || {} })), _jsx(Box, Object.assign({ width: "100%", mb: "16px" }, { children: _jsx(StringPropertyEditor, { propDef: {
                                    type: "string",
                                    options: {
                                        format: "text",
                                    },
                                }, propName: "Event name", value: action.eventName || "", onChange: handleEventNameChange }) })), _jsx(Box, Object.assign({ width: "100%", mb: "16px" }, { children: _jsxs(Grid, Object.assign({ templateColumns: "repeat(6, 1fr)", gap: 2, alignItems: "center" }, { children: [_jsx(GridItem, Object.assign({ colSpan: 5 }, { children: _jsx(StringPropertyEditor, { propDef: {
                                                type: "string",
                                                options: {
                                                    format: "select",
                                                    options: fieldsVariables.map((field) => ({
                                                        label: field.display,
                                                        value: field.id,
                                                    })),
                                                },
                                            }, propName: "Action name", value: action.actionName, onChange: handleChange }) })), _jsx(GridItem, Object.assign({ colSpan: 1 }, { children: _jsx(Tooltip, Object.assign({ label: "Payload" }, { children: _jsx(Flex, Object.assign({ alignItems: "center" }, { children: _jsx(Button, Object.assign({ px: "2", py: "1", fontWeight: "bold", rounded: "sm", display: "inline-block", bg: action.payload ? "#0065ff" : "white", color: action.payload ? "white" : "black", onClick: () => setActionModal("payload") }, { children: "{ }" })) })) })) }))] })) })), _jsxs(Box, Object.assign({ width: "100%", mb: "16px" }, { children: [_jsxs(Box, Object.assign({ width: "100%", mb: "16px" }, { children: [_jsx(Text, Object.assign({ mb: "4px" }, { children: "On Success" })), _jsx(Select, Object.assign({ mt: "8px", width: "100%", size: "sm", value: ((_a = action.onSuccess) === null || _a === void 0 ? void 0 : _a.type) || "none", onChange: onChangePostActionTypeHandlers.onSuccess }, { children: Object.keys(ActionPropertyBuildersMap).map((action) => (_jsx("option", Object.assign({ value: action }, { children: humanize(action) }), action))) }))] })), _jsx(OnSuccessActionProperty, { action: action.onSuccess || { type: "none" }, onChange: onSavePostActionHandlers.onSuccess })] })), _jsxs(Box, Object.assign({ width: "100%", mb: "16px" }, { children: [_jsxs(Box, Object.assign({ width: "100%", mb: "16px" }, { children: [_jsx(Text, Object.assign({ mb: "4px" }, { children: "On Fail" })), _jsx(Select, Object.assign({ mt: "8px", width: "100%", size: "sm", value: ((_b = action.onFail) === null || _b === void 0 ? void 0 : _b.type) || "none", onChange: onChangePostActionTypeHandlers.onFail }, { children: Object.keys(ActionPropertyBuildersMap).map((action) => (_jsx("option", Object.assign({ value: action }, { children: humanize(action) }), action))) }))] })), _jsx(OnFailActionProperty, { action: action.onFail || { type: "none" }, onChange: onSavePostActionHandlers.onFail })] })), _jsxs(Box, Object.assign({ width: "100%", mb: "16px" }, { children: [_jsxs(Flex, Object.assign({ my: "8px" }, { children: [_jsx(Text, Object.assign({ fontWeight: "bold" }, { children: "Response messages display" })), _jsx(Spacer, {}), _jsx(Switch, { disabled: !action.showNotification, defaultChecked: action.showNotification, onChange: onToggleNotification })] })), _jsxs(Text, { children: ["This option is deprecated. use", " ", _jsx("strong", { children: "\"Show Toast\"" }), " action to show a message."] }), action.showNotification && (_jsx(Stack, Object.assign({ mt: "2", spacing: 2, pb: 4 }, { children: _jsxs(VStack, { children: [_jsxs(Box, Object.assign({ width: "100%" }, { children: [actionModal === "onSuccessMessage" && (_jsx(ToastEditorModal, { onClose: () => setActionModal(null), onSave: onSaveMessageHandlers.onSuccess, value: action.notification.onSuccess, variant: "success" })), _jsxs(Flex, Object.assign({ my: "8px" }, { children: [_jsx(Text, Object.assign({ color: "gray.400" }, { children: "Success notification" })), _jsx(Spacer, {}), _jsx(Button, Object.assign({ variant: "link", color: "blue", fontWeight: "normal", onClick: () => setActionModal("onSuccessMessage"), size: "sm", disabled: true }, { children: "Edit messages" }))] })), _jsx(ToastNotificationComponent, { variant: "muted", title: action.notification.onSuccess.title, description: action.notification.onSuccess.description })] })), _jsxs(Box, Object.assign({ width: "100%" }, { children: [actionModal === "onFailMessage" && (_jsx(ToastEditorModal, { onClose: () => setActionModal(null), onSave: onSaveMessageHandlers.onFail, value: action.notification.onFail, variant: "error" })), _jsxs(Flex, Object.assign({ my: "8px" }, { children: [_jsx(Text, Object.assign({ color: "gray.400" }, { children: "Error notification" })), _jsx(Spacer, {}), _jsx(Button, Object.assign({ variant: "link", color: "blue", fontWeight: "normal", onClick: () => setActionModal("onFailMessage"), size: "sm", disabled: true }, { children: "Edit messages" }))] })), _jsx(ToastNotificationComponent, { variant: "muted", title: action.notification.onFail.title, description: action.notification.onFail.description })] }))] }) })))] }))] })) })));
        },
    },
    jump_to_page: {
        icon: Redo,
        component: (props) => {
            const pagesMap = RuntimeContext.useSelectState((state) => state.maps.page);
            const pages = React.useMemo(() => Iterator.from(Object.values(pagesMap))
                .map((filterPage) => ({
                value: filterPage.id,
                label: format(filterPage.title, {}),
            }))
                .toArray(), [pagesMap]);
            const [state, setState] = React.useState({ action: props.action });
            const [stateAction] = useDebounce(state.action, 300);
            React.useEffect(() => {
                props.onChange(stateAction);
            }, [stateAction]);
            const handlePageIDChange = React.useCallback((pageID) => {
                setState((state) => produce(state, (draft) => {
                    draft.action.pageID = pageID;
                }));
            }, []);
            const page = RuntimeContext.useSelectState((state_) => state_.maps.page[state.action.pageID]);
            const handleParamChange = React.useCallback((key, val) => {
                setState((state) => produce(state, (draft) => {
                    if (!draft.action.params) {
                        draft.action.params = {};
                    }
                    draft.action.params[key] = val;
                }));
            }, []);
            const handleMotionDirection = React.useCallback((type) => {
                setState((state) => produce(state, (draft) => {
                    draft.action.direction = type;
                }));
            }, []);
            const handleEventNameChange = React.useCallback((eventName) => {
                setState((state) => produce(state, (draft) => {
                    draft.action.eventName = eventName;
                }));
            }, []);
            const handleBackNavigation = React.useCallback((isAllowed) => {
                setState((state) => produce(state, (draft) => {
                    draft.action.allowBackNavigation = isAllowed;
                }));
            }, []);
            const params = React.useMemo(() => (Object.assign({ rowId: state.action.rowID }, Object.fromEntries(Object.keys((page === null || page === void 0 ? void 0 : page.params) || {})
                .concat("rowId")
                .map((key) => { var _a, _b; return [key, (_b = (_a = state.action.params) === null || _a === void 0 ? void 0 : _a[key]) !== null && _b !== void 0 ? _b : ""]; })))), [state.action.rowID, page === null || page === void 0 ? void 0 : page.params, state.action.params]);
            return (_jsx(PropsGroup, Object.assign({ name: "Destination", style: actionDrawerStyle }, { children: _jsxs(VStack, Object.assign({ alignItems: "normal", mt: "10px" }, { children: [_jsx(Box, { children: _jsx(StringPropertyEditor, { propDef: {
                                    type: "string",
                                    options: {
                                        format: "text",
                                    },
                                }, propName: "Event name", value: state.action.eventName || "", onChange: handleEventNameChange }) }), _jsxs(Box, { children: [_jsx(FormLabel, { children: "Select page" }), _jsx(StringPropertyEditor, { propDef: {
                                        type: "string",
                                        options: { format: "select", options: pages },
                                    }, propName: "Page target", value: state.action.pageID, onChange: handlePageIDChange })] }), Object.keys(params).map((key) => (_jsxs(SimpleGrid, Object.assign({ columns: 2 }, { children: [_jsx(Box, Object.assign({ alignSelf: "center" }, { children: _jsx(Text, { children: key }) })), _jsx(ExpressionPropertyEditor, { propDef: {
                                        type: "expression",
                                        options: {},
                                    }, propName: key, value: (params === null || params === void 0 ? void 0 : params[key]) || "", onChange: (val) => handleParamChange(key, val) })] }), key))), _jsxs(HStack, { children: [_jsx(Text, { children: "Allow Back Navigation" }), _jsx(Spacer, {}), _jsx(Switch, { isChecked: state.action.allowBackNavigation, onChange: (e) => handleBackNavigation(e.target.checked) })] }), _jsxs(Box, { children: [_jsx(FormLabel, { children: "Transition Type" }), _jsx(Box, { children: _jsx(StringPropertyEditor, { propDef: {
                                            type: "string",
                                            options: {
                                                format: "select",
                                                options: motionType.map((type) => ({
                                                    label: type,
                                                    value: camelCase(type),
                                                })),
                                            },
                                        }, propName: "Motion Type", value: state.action.direction || "slideRight", onChange: handleMotionDirection }) })] })] })) })));
        },
    },
    trigger_pipeline: {
        icon: Sitemap,
        provides: ["response.statusCode", "response.message"],
        component: (props) => {
            const config = RuntimeContext.useSelectState((state) => state.config);
            const [state, setState] = React.useState({
                action: props.action,
                workflows: [],
                triggers: [],
            });
            const [stateAction] = useDebounce(state.action, 300);
            React.useEffect(() => {
                props.onChange(stateAction);
            }, [stateAction]);
            const [actionModal, setActionModal] = React.useState(null);
            const { isOpen, onOpen, onClose } = useDisclosure();
            const { data: releases } = qoreStorageClient
                .table("release_log")
                .useListRow({
                condition: {
                    release: {
                        project: config.projectID,
                    },
                    stage: "staging",
                },
                orderBy: {
                    updated_at: "DESC",
                },
                limit: 1,
            }, {
                skip: !config,
            });
            const qorePipelineEndpoint = React.useMemo(() => {
                var _a, _b;
                const endpoint = (_b = (_a = releases === null || releases === void 0 ? void 0 : releases[0]) === null || _a === void 0 ? void 0 : _a.user_overrides) === null || _b === void 0 ? void 0 : _b["qore-pipeline"].domains.split(",")[0];
                return endpoint && `//${endpoint}`;
            }, [releases]);
            const adminSecret = React.useMemo(() => { var _a, _b; return (_b = (_a = releases === null || releases === void 0 ? void 0 : releases[0]) === null || _a === void 0 ? void 0 : _a.user_overrides) === null || _b === void 0 ? void 0 : _b["qore-pipeline"].admin_secret; }, [releases]);
            // eslint-disable-next-line @typescript-eslint/no-unused-vars -- might used this later
            const { data: _ } = useSWRImmutable([qorePipelineEndpoint, "schema"], (url) => __awaiter(void 0, void 0, void 0, function* () {
                const workflowsResp = yield fetch(`${url}/api/workflows`, {
                    method: "GET",
                    headers: {
                        "x-qonduit-admin-secret": adminSecret,
                    },
                });
                const workflows = yield workflowsResp.json();
                setState((state) => produce(state, (draft) => {
                    draft.workflows = workflows;
                    draft.action.pipelineEndpoint = url;
                }));
            }), {
                isPaused: () => !(qorePipelineEndpoint && adminSecret),
            });
            const fetchTriggers = React.useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
                try {
                    if (!!qorePipelineEndpoint && state.action.pipelineID) {
                        const triggersResp = yield fetch(`${qorePipelineEndpoint}/api/workflows/${state.action.pipelineID}/triggers`, {
                            method: "GET",
                            headers: {
                                "x-qonduit-admin-secret": adminSecret,
                            },
                        });
                        const triggers = yield triggersResp.json();
                        setState((state) => produce(state, (draft) => {
                            draft.triggers = triggers;
                        }));
                    }
                }
                catch (error) { }
            }), [qorePipelineEndpoint, state.action.pipelineID, adminSecret]);
            const formattedWorkflows = React.useMemo(() => {
                return state.workflows.map((item) => ({
                    label: (item === null || item === void 0 ? void 0 : item.title) || "",
                    value: (item === null || item === void 0 ? void 0 : item.id) || "",
                }));
            }, [state.workflows]);
            const formattedTriggers = React.useMemo(() => {
                return state.triggers.map((item) => ({
                    label: (item === null || item === void 0 ? void 0 : item.name) || "",
                    value: (item === null || item === void 0 ? void 0 : item.id) || "",
                }));
            }, [state.triggers]);
            const handleWorkflowChange = React.useCallback((workflowID) => {
                setState((state) => produce(state, (draft) => {
                    draft.action.pipelineID = workflowID;
                }));
            }, []);
            const handleTriggerChange = React.useCallback((triggerID) => {
                setState((state) => produce(state, (draft) => {
                    draft.action.triggerID = triggerID;
                }));
            }, []);
            const handleSavePayload = React.useCallback((payload) => {
                setState((action) => produce(action, (draft) => {
                    draft.action.payload = payload;
                }));
            }, []);
            React.useEffect(() => {
                fetchTriggers();
            }, [fetchTriggers]);
            const TriggersSelector = React.useCallback(() => {
                return (_jsx(StringPropertyEditor, { propDef: {
                        type: "string",
                        options: { format: "select", options: formattedTriggers },
                    }, propName: "TriggerSelector", value: props.action.triggerID, onChange: handleTriggerChange }));
            }, [formattedTriggers, props.action.triggerID]);
            const PipelineSelector = React.useCallback(() => {
                return (_jsx(StringPropertyEditor, { propDef: {
                        type: "string",
                        options: { format: "select", options: formattedWorkflows },
                    }, propName: "WorkflowSelector", value: props.action.pipelineID, onChange: handleWorkflowChange }));
            }, [formattedWorkflows, props.action.pipelineID]);
            const onToggleNotification = React.useCallback((event) => {
                setState((state) => produce(state, (draft) => {
                    draft.action.showNotification = event.currentTarget.checked;
                }));
            }, []);
            const onSaveMessageHandlers = React.useMemo(() => {
                const onSaveMessage = (type) => (value) => {
                    setState((state) => produce(state, (draft) => {
                        draft.action.notification[type] = value;
                    }));
                };
                return {
                    onSuccess: onSaveMessage("onSuccess"),
                    onFail: onSaveMessage("onFail"),
                };
            }, []);
            React.useEffect(() => {
                var _a;
                (_a = props.handleModalDisclosure) === null || _a === void 0 ? void 0 : _a.call(props, !!actionModal || isOpen);
            }, [actionModal, isOpen]);
            return (_jsxs(PropsGroup, Object.assign({ name: "Trigger", style: actionDrawerStyle }, { children: [_jsxs(Box, { children: [_jsxs(Box, { children: [_jsx(Text, Object.assign({ mb: "4px" }, { children: "Choose pipeline" })), _jsx(PipelineSelector, {})] }), _jsxs(Box, Object.assign({ my: "24px", h: "44px" }, { children: [_jsx(Text, Object.assign({ mb: "4px" }, { children: "Choose trigger" })), _jsx(TriggersSelector, {})] })), _jsx(Box, Object.assign({ mt: "48px", mb: "16px", display: "flex" }, { children: _jsx(Button, Object.assign({ colorScheme: "gray", variant: "outline", leftIcon: _jsx(Icon, { as: iconsList["Analyse"] }), onClick: onOpen, flex: "1", size: "sm" }, { children: "Setting payload" })) })), isOpen && (_jsx(PayloadEditor, { defaultPayload: state.action.payload || {}, onSave: handleSavePayload, onClose: onClose }))] }), _jsxs(Box, Object.assign({ width: "100%", my: "24px" }, { children: [_jsxs(Flex, Object.assign({ my: "8px" }, { children: [_jsx(Text, Object.assign({ fontWeight: "bold" }, { children: "Response messages display" })), _jsx(Spacer, {}), _jsx(Switch, { disabled: !state.action.showNotification, defaultChecked: state.action.showNotification, onChange: onToggleNotification })] })), _jsxs(Text, { children: ["This option is deprecated. use", " ", _jsx("strong", { children: "\"Show Toast\"" }), " action to show a message."] }), state.action.showNotification && (_jsx(Stack, Object.assign({ mt: "2", spacing: 2, pb: 4 }, { children: _jsxs(VStack, { children: [_jsxs(Box, Object.assign({ width: "100%" }, { children: [actionModal === "onSuccessMessage" && (_jsx(ToastEditorModal, { onClose: () => setActionModal(null), onSave: onSaveMessageHandlers.onSuccess, value: state.action.notification.onSuccess, variant: "success" })), _jsxs(Flex, Object.assign({ my: "8px" }, { children: [_jsx(Text, Object.assign({ color: "gray.400" }, { children: "Success notification" })), _jsx(Spacer, {}), _jsx(Button, Object.assign({ variant: "link", color: "blue", fontWeight: "normal", onClick: () => setActionModal("onSuccessMessage"), size: "sm", disabled: true }, { children: "Edit messages" }))] })), _jsx(ToastNotificationComponent, { variant: "muted", title: state.action.notification.onSuccess.title, description: state.action.notification.onSuccess.description })] })), _jsxs(Box, Object.assign({ width: "100%" }, { children: [actionModal === "onFailMessage" && (_jsx(ToastEditorModal, { onClose: () => setActionModal(null), onSave: onSaveMessageHandlers.onFail, value: state.action.notification.onFail, variant: "error" })), _jsxs(Flex, Object.assign({ my: "8px" }, { children: [_jsx(Text, Object.assign({ color: "gray.400" }, { children: "Error notification" })), _jsx(Spacer, {}), _jsx(Button, Object.assign({ variant: "link", color: "blue", fontWeight: "normal", onClick: () => setActionModal("onFailMessage"), size: "sm", disabled: true }, { children: "Edit messages" }))] })), _jsx(ToastNotificationComponent, { variant: "muted", title: state.action.notification.onFail.title, description: state.action.notification.onFail.description })] }))] }) })))] }))] })));
        },
    },
    scan_QR_code: {
        icon: Scan,
        component: (props) => {
            var _a;
            const [action, setAction] = React.useState(props.action);
            const [QRAction] = useDebounce(action, 300);
            React.useEffect(() => {
                props.onChange(QRAction);
            }, [QRAction]);
            const handleVariableOutput = React.useCallback((e) => {
                setAction((action) => (Object.assign(Object.assign({}, action), { variableOutput: e.target.value })));
            }, []);
            const handleMessage = React.useCallback((e) => {
                setAction((action) => (Object.assign(Object.assign({}, action), { message: e.target.value })));
            }, []);
            const OnSuccessActionProperty = React.useMemo(() => { var _a; return ActionPropertyBuildersMap[((_a = action.onSuccess) === null || _a === void 0 ? void 0 : _a.type) || "none"].component; }, [action.onSuccess, ActionPropertyBuildersMap]);
            const onChangePostActionTypeHandlers = React.useMemo(() => {
                const onChangePostActionType = (type) => (e) => setAction((action) => produce(action, (draft) => {
                    draft[type] =
                        actionTypeDefaultValues[e.target.value];
                }));
                return {
                    onSuccess: onChangePostActionType("onSuccess"),
                    onFail: onChangePostActionType("onFail"),
                };
            }, [action]);
            const onSavePostActionHandlers = React.useMemo(() => {
                const onSavePostAction = (type) => (postAction) => {
                    setAction((action) => produce(action, (draft) => {
                        draft[type] = postAction;
                    }));
                };
                return {
                    onSuccess: onSavePostAction("onSuccess"),
                    onFail: onSavePostAction("onFail"),
                };
            }, [action]);
            return (_jsxs(PropsGroup, Object.assign({ name: "QR-Code", style: actionDrawerStyle }, { children: [_jsxs(Box, Object.assign({ backgroundColor: "#F5F5F5", p: "8px", mb: "16px" }, { children: [_jsxs(Box, Object.assign({ mb: "8px" }, { children: [_jsxs(HStack, Object.assign({ mb: "8px", spacing: "8px", alignItems: "center" }, { children: [_jsx(Text, { children: "Variable output" }), _jsx(Tooltip, Object.assign({ width: "196px", hasArrow: true, label: _jsxs(_Fragment, { children: [_jsx(Text, Object.assign({ color: "white", fontSize: "xs" }, { children: "You can mention this variable to get the scanned code." })), _jsx("br", {}), _jsx(Text, Object.assign({ color: "white", fontSize: "xs" }, { children: "ex: @action.QRScan.[variable]" }))] }) }, { children: _jsx(Box, { children: _jsx(Icon, { as: iconsList["Information"] }) }) }))] })), _jsx(Input, { size: "sm", placeholder: "please input an id", backgroundColor: "white", value: action.variableOutput, onChange: handleVariableOutput })] })), _jsx(Text, Object.assign({ mb: "8px" }, { children: "Message" })), _jsx(Textarea, { backgroundColor: "white", size: "sm", placeholder: "Align QR code within the frame to scan", value: action.message, onChange: handleMessage })] })), _jsxs(Box, Object.assign({ width: "100%", mb: "16px" }, { children: [_jsxs(Box, Object.assign({ width: "100%", mb: "16px" }, { children: [_jsx(Text, Object.assign({ mb: "4px" }, { children: "On Success" })), _jsx(Select, Object.assign({ mt: "8px", width: "100%", size: "sm", value: ((_a = action.onSuccess) === null || _a === void 0 ? void 0 : _a.type) || "none", onChange: onChangePostActionTypeHandlers.onSuccess }, { children: Object.keys(ActionPropertyBuildersMap)
                                            .filter((action) => action !== "scan_QR_code")
                                            .map((action) => (_jsx("option", Object.assign({ value: action }, { children: humanize(action) }), action))) }))] })), _jsx(OnSuccessActionProperty, { action: action.onSuccess || { type: "none" }, onChange: onSavePostActionHandlers.onSuccess })] }))] })));
        },
    },
    open_as_modal: {
        icon: OpenModal,
        component: (props) => {
            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]);
            const [state, setState] = React.useState({ action: props.action });
            const [actionState] = useDebounce(state.action, 300);
            React.useEffect(() => {
                props.onChange(actionState);
            }, [actionState]);
            const handlePageIDChange = React.useCallback((pageID) => {
                setState((state) => produce(state, (draft) => {
                    draft.action.pageID = pageID;
                }));
            }, []);
            const page = RuntimeContext.useSelectState((state_) => state_.maps.page[state.action.pageID]);
            const params = React.useMemo(() => (Object.assign({ rowId: state.action.rowID }, Object.fromEntries(Object.keys((page === null || page === void 0 ? void 0 : page.params) || {})
                .concat("rowId")
                .map((key) => { var _a, _b; return [key, (_b = (_a = state.action.params) === null || _a === void 0 ? void 0 : _a[key]) !== null && _b !== void 0 ? _b : ""]; })))), [state.action.rowID, page === null || page === void 0 ? void 0 : page.params, state.action.params]);
            const handleParamChange = React.useCallback((key, val) => {
                setState((state) => produce(state, (draft) => {
                    if (!draft.action.params) {
                        draft.action.params = {};
                    }
                    draft.action.params[key] = val;
                }));
            }, []);
            const handleHeightChange = React.useCallback((height) => {
                setState((state) => produce(state, (draft) => {
                    draft.action.height = height;
                }));
            }, []);
            const handleModalDirection = React.useCallback((type) => {
                setState((state) => produce(state, (draft) => {
                    draft.action.direction = type;
                }));
            }, []);
            return (_jsx(PropsGroup, Object.assign({ name: "Open modal", style: actionDrawerStyle }, { children: _jsxs(VStack, Object.assign({ spacing: "24px", alignItems: "stretch" }, { children: [_jsxs(Box, Object.assign({ h: "44px" }, { children: [_jsx(Text, { children: "Page" }), _jsx(Box, { children: _jsx(StringPropertyEditor, { propDef: {
                                            type: "string",
                                            options: { format: "select", options: pages },
                                        }, propName: "Page target", value: state.action.pageID, onChange: handlePageIDChange }) })] })), Object.keys(params).map((key) => (_jsxs(SimpleGrid, Object.assign({ columns: 2 }, { children: [_jsx(Box, Object.assign({ alignSelf: "center" }, { children: _jsx(Text, { children: key }) })), _jsx(ExpressionPropertyEditor, { propDef: {
                                        type: "expression",
                                        options: {},
                                    }, propName: key, value: (params === null || params === void 0 ? void 0 : params[key]) || "", onChange: (val) => handleParamChange(key, val) })] }), key))), _jsxs(Box, { children: [_jsx(Text, { children: "Height" }), _jsx(StringPropertyEditor, { propDef: {
                                        type: "string",
                                        options: {
                                            format: "select",
                                            options: [
                                                {
                                                    label: "Small",
                                                    value: "25%",
                                                },
                                                {
                                                    label: "Medium",
                                                    value: "50%",
                                                },
                                                {
                                                    label: "Large",
                                                    value: "75%",
                                                },
                                                {
                                                    label: "Full page",
                                                    value: "100%",
                                                },
                                            ],
                                        },
                                    }, propName: "Height", value: state.action.height, onChange: handleHeightChange })] }), _jsxs(Box, { children: [_jsx(FormLabel, { children: "Transition Type" }), _jsx(Box, { children: _jsx(StringPropertyEditor, { propDef: {
                                            type: "string",
                                            options: {
                                                format: "select",
                                                options: modalMotionType.map((type) => ({
                                                    label: type,
                                                    value: camelCase(type),
                                                })),
                                            },
                                        }, propName: "Motion Type", value: state.action.direction || "scale", onChange: handleModalDirection }) })] })] })) })));
        },
    },
    close_page_modal: {
        icon: CloseModal,
        component: (props) => {
            var _a;
            const [action, setAction] = React.useState(props.action);
            const [closeAction] = useDebounce(action, 300);
            React.useEffect(() => {
                props.onChange(closeAction);
            }, [closeAction]);
            const onCloseActionTypeHandlers = React.useCallback((e) => setAction((action) => produce(action, (draft) => {
                draft["onClose"] =
                    actionTypeDefaultValues[e.target.value];
            })), [action]);
            const OnCloseActionProperty = React.useMemo(() => { var _a; return ActionPropertyBuildersMap[((_a = action.onClose) === null || _a === void 0 ? void 0 : _a.type) || "none"].component; }, [action.onClose, ActionPropertyBuildersMap]);
            const onSavePostActionHandlers = React.useCallback((postAction) => {
                setAction((action) => produce(action, (draft) => {
                    draft["onClose"] = postAction;
                }));
            }, [action]);
            return (_jsxs(PropsGroup, Object.assign({ name: "Close modal", style: actionDrawerStyle }, { children: [_jsxs(Box, Object.assign({ width: "100%", mb: "16px" }, { children: [_jsx(Text, Object.assign({ mb: "4px" }, { children: "On Close" })), _jsx(Select, Object.assign({ mt: "8px", width: "100%", size: "sm", value: ((_a = action.onClose) === null || _a === void 0 ? void 0 : _a.type) || "none", onChange: onCloseActionTypeHandlers }, { children: Object.keys(ActionPropertyBuildersMap)
                                    .filter((action) => action !== "close_page_modal")
                                    .map((action) => (_jsx("option", Object.assign({ value: action }, { children: humanize(action) }), action))) }))] })), _jsx(OnCloseActionProperty, { action: action.onClose || { type: "none" }, onChange: onSavePostActionHandlers })] })));
        },
    },
    show_toast: {
        icon: Loader,
        component: (props) => {
            const showToastStatusList = ["info", "success", "warning", "error"];
            const [action, setAction] = React.useState(Object.assign(Object.assign({}, actionTypeDefaultValues.show_toast), props.action));
            const [stateAction] = useDebounce(action, 300);
            React.useEffect(() => {
                props.onChange(stateAction);
            }, [stateAction]);
            const handleStyleToastChange = React.useCallback((styles) => {
                setAction((state) => produce(state, (draft) => {
                    if (showToastStatusList.includes(styles)) {
                        draft.status = styles;
                    }
                }));
            }, []);
            const handleTitleChange = React.useCallback((title) => {
                setAction((state) => produce(state, (draft) => {
                    draft.title = title;
                }));
            }, []);
            const handleSubtitleChange = React.useCallback((subtitle) => {
                setAction((state) => produce(state, (draft) => {
                    draft.subtitle = subtitle;
                }));
            }, []);
            return (_jsx(PropsGroup, Object.assign({ name: "Toast content", style: actionDrawerStyle }, { children: _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, { children: _jsx(FormLabel, { children: "Style" }) }) })), _jsx(GridItem, Object.assign({ colSpan: 9, maxW: "full", alignItems: "center", justifyContent: "flex-end" }, { children: _jsx(StringPropertyEditor, { propDef: {
                                    type: "string",
                                    options: {
                                        format: "select",
                                        options: showToastStatusList.map((styles) => ({
                                            label: styles,
                                            value: styles,
                                        })),
                                    },
                                }, propName: "StyleToast", value: action.status, onChange: handleStyleToastChange }) })), _jsx(GridItem, Object.assign({ colSpan: 3, maxW: "full", display: "flex" }, { children: _jsx(HStack, { children: _jsx(FormLabel, { children: "Title" }) }) })), _jsx(GridItem, Object.assign({ colSpan: 9, maxW: "full", alignItems: "center", justifyContent: "flex-end" }, { children: _jsx(StringPropertyEditor, { propDef: {
                                    type: "string",
                                    options: { format: "text" },
                                }, propName: "Title", value: action.title, onChange: handleTitleChange }) })), _jsx(GridItem, Object.assign({ colSpan: 3, maxW: "full", display: "flex" }, { children: _jsx(HStack, { children: _jsx(FormLabel, { children: "Subtitle" }) }) })), _jsx(GridItem, Object.assign({ colSpan: 9, maxW: "full", alignItems: "center", justifyContent: "flex-end" }, { children: _jsx(StringPropertyEditor, { propDef: {
                                    type: "string",
                                    options: { format: "text" },
                                }, propName: "Subtitle", value: action.subtitle, onChange: handleSubtitleChange }) }))] })) })));
        },
    },
    request_recover_account: {
        icon: Loader,
        component: (props) => {
            const pagesMap = RuntimeContext.useSelectState((state) => state.maps.page);
            const pages = React.useMemo(() => Iterator.from(Object.values(pagesMap))
                .map((filterPage) => ({
                value: filterPage.id,
                label: format(filterPage.title, {}),
            }))
                .toArray(), [pagesMap]);
            return (_jsx(PropsGroup, Object.assign({ name: "Recover Account", style: actionDrawerStyle }, { children: _jsxs(VStack, Object.assign({ alignItems: "normal", mt: "10px" }, { children: [_jsxs(Box, { children: [_jsx(FormLabel, { children: "Select page" }), _jsx(StringPropertyEditor, { propDef: {
                                        type: "string",
                                        options: { format: "select", options: pages },
                                    }, propName: "Page target", value: props.action.redirectPage, onChange: (redirectPage) => props.onChange(Object.assign(Object.assign({}, props.action), { redirectPage })) })] }), _jsx(Box, { children: _jsx(StringPropertyEditor, { propDef: {
                                    type: "string",
                                    options: { format: "text" },
                                }, propName: "Identifier", value: props.action.identifier, onChange: (identifier) => {
                                    props.onChange(Object.assign(Object.assign({}, props.action), { identifier }));
                                } }) })] })) })));
        },
    },
    recover_account: {
        icon: Loader,
        component: (props) => {
            return (_jsx(PropsGroup, Object.assign({ name: "Recover Account", style: actionDrawerStyle }, { children: _jsxs(VStack, Object.assign({ alignItems: "normal", mt: "10px" }, { children: [_jsx(Box, { children: _jsx(StringPropertyEditor, { propDef: {
                                    type: "string",
                                    options: { format: "text" },
                                }, propName: "Token", value: props.action.token, onChange: (token) => {
                                    props.onChange(Object.assign(Object.assign({}, props.action), { token }));
                                } }) }), _jsx(Box, { children: _jsx(StringPropertyEditor, { propDef: {
                                    type: "string",
                                    options: { format: "text" },
                                }, propName: "Password", value: props.action.password, onChange: (password) => {
                                    props.onChange(Object.assign(Object.assign({}, props.action), { password }));
                                } }) })] })) })));
        },
    },
};
const actionTypeDefaultValues = {
    none: { type: "none", onError: [{ type: "none" }] },
    logout: { id: "", type: "logout" },
    back_to_login: { id: "", type: "back_to_login" },
    refresh_data: { id: "", type: "refresh_data" },
    view_detail: {
        id: "",
        type: "view_detail",
        pageID: nanoid(3),
        rowID: "@[item.id](item.id)",
    },
    open_link: { id: "", type: "open_link", link: "https://google.com" },
    trigger_action: {
        id: "",
        type: "trigger_action",
        actionName: "",
        payload: {},
        onSuccess: { type: "none" },
        onFail: { type: "none" },
        showNotification: false,
        notification: {
            onSuccess: {
                title: "Success",
                description: "Your request successfully executed",
            },
            onFail: {
                title: "Failed",
                description: "Oops, there is something wrong!",
            },
        },
    },
    jump_to_page: {
        id: "",
        type: "jump_to_page",
        pageID: "",
        direction: "slideRight",
        allowBackNavigation: false,
    },
    trigger_pipeline: {
        id: "",
        type: "trigger_pipeline",
        pipelineID: "",
        triggerID: "",
        pipelineEndpoint: "",
        payload: {},
        showNotification: false,
        notification: {
            onSuccess: {
                title: "Success",
                description: "Your request successfully executed",
            },
            onFail: {
                title: "Failed",
                description: "Oops, there is something wrong!",
            },
        },
    },
    scan_QR_code: {
        id: "",
        type: "scan_QR_code",
        variableOutput: "variable",
        message: "Align QR code within the frame to scan",
        onSuccess: { type: "none" },
    },
    open_as_modal: {
        id: "",
        type: "open_as_modal",
        pageID: "",
        height: "50%",
        direction: "scale",
    },
    close_page_modal: {
        id: "",
        type: "close_page_modal",
        onClose: { type: "none" },
    },
    show_toast: {
        id: "",
        type: "show_toast",
        title: "",
        subtitle: "",
        status: "info",
    },
    login: {
        id: "",
        type: "login",
        username: "",
        password: "",
    },
    request_recover_account: {
        id: "",
        type: "request_recover_account",
        redirectPage: nanoid(3),
        identifier: "",
    },
    recover_account: {
        id: "",
        type: "recover_account",
        token: "",
        password: "@[input.password](input.password)",
    },
};
const DrawerActionSettings = ({ selectedAction, pageID, drawerDisclosure, handleActionChange, variables, }) => {
    var _a;
    if (!selectedAction)
        return _jsx(_Fragment, {});
    const [isOpenComponentModal, setIsOpenComponentModal] = React.useState(false);
    const { componentRef } = useVariablesContext();
    const ref = React.useRef(null);
    const variables_ = React.useMemo(() => variables.map((variable) => ({
        id: variable,
        display: variable,
    })), [variables]);
    const actionOptions = React.useMemo(() => Object.keys(ActionPropertyBuildersMap).filter((action) => action !== "none"), [ActionPropertyBuildersMap]);
    const Comp = React.useMemo(() => {
        var _a;
        return (_a = ActionPropertyBuildersMap[selectedAction.type]) === null || _a === void 0 ? void 0 : _a.component;
    }, [selectedAction.type, ActionPropertyBuildersMap]);
    const handleChangeActionType = React.useCallback((e) => handleActionChange(Object.assign(Object.assign({}, actionTypeDefaultValues[e.currentTarget.value]), { id: selectedAction.id })), [selectedAction.id]);
    return (_jsx(Portal, { children: _jsx(Box, Object.assign({ css: css `
          .chakra-modal__content-container {
            width: ${isOpenComponentModal ? "100vw" : "0vw"} !important;
          }
        `, ref: ref }, { children: _jsx(Drawer, Object.assign({ isOpen: drawerDisclosure.isOpen, onClose: null, placement: "right", portalProps: { containerRef: ref }, blockScrollOnMount: false }, { children: _jsx(DrawerContent, Object.assign({ borderColor: "#E2E8F0", height: "calc(100% - 49px)", borderRadius: "0px", transform: "none !important", boxShadow: "unset", css: css `
              top: inherit !important;
              max-width: unset;
              width: ${((_a = componentRef === null || componentRef === void 0 ? void 0 : componentRef.divElement) === null || _a === void 0 ? void 0 : _a.offsetWidth) || 0}px !important;
            ` }, { children: _jsx(DrawerBody, Object.assign({ padding: "0px", overflow: "unset" }, { children: _jsxs(VariablesProvider, Object.assign({ variables: variables_ }, { children: [_jsxs(HStack, Object.assign({ h: "2.6rem", paddingX: "15px", spacing: "12px", borderTopWidth: "1px", borderBottomWidth: "2px", borderColor: "#E2E8F0" }, { children: [_jsx(ArrowLeft, { fontSize: "18px", color: "#171717", onClick: drawerDisclosure.onClose, cursor: "pointer" }), _jsx(Text, { children: "Action Settings" })] })), _jsx(Box, Object.assign({ backgroundColor: "#F5F5F5", boxShadow: "inset 0px -1px 0px #E9E9E9", padding: "8px 12px" }, { children: _jsxs(Menu, Object.assign({ autoSelect: false, isLazy: true, placement: "bottom" }, { children: [_jsx(MenuButton, Object.assign({ px: 4, py: 2, width: "full", transition: "all 0.2s", borderRadius: "md", borderWidth: "1px", outline: "unset", bg: "white", _hover: { bg: "white" }, _expanded: { bg: "white" } }, { children: _jsxs(HStack, { children: [_jsx(Icon, { as: ActionPropertyBuildersMap[selectedAction.type].icon }), _jsx(Text, { children: humanize(selectedAction.type) }), _jsx(Spacer, {}), _jsx(ChevronDown, { fontSize: "20px", color: "#A2A2A2" })] }) })), _jsx(MenuList, { children: actionOptions.map((action) => pageID !== "register" &&
                                                    action === "back_to_login" ? null : (_jsx(MenuItem, Object.assign({ value: action, bg: humanize(action) ===
                                                        humanize(selectedAction.type) && "gray.200", icon: _jsx(Center, { children: _jsx(Icon, { as: ActionPropertyBuildersMap[action].icon, fontSize: "16px" }) }), onClick: handleChangeActionType }, { children: humanize(action) }), action))) })] })) })), _jsxs(Scrollbars, { children: [_jsx(Box, Object.assign({ paddingX: 4, borderBottom: "1px", borderColor: "gray.300" }, { children: _jsx(Comp, { onChange: handleActionChange, action: selectedAction, handleModalDisclosure: (isOpen) => setIsOpenComponentModal(isOpen) }, selectedAction.id || "none") })), _jsx(Spacer, { h: "36" })] })] })) })) })) })) })) }));
};
const ActionComponent = ({ type, children, actionOptions, pageID, handleActionAddType, handleRemoveAction, onDragEnd, actions, handleMoveToDrawerAction, }) => {
    return (_jsxs(_Fragment, { children: [_jsxs(HStack, { children: [_jsx(Center, { children: children }), _jsx(Spacer, {}), _jsxs(Menu, Object.assign({ autoSelect: false, isLazy: true }, { children: [_jsx(MenuButton, { as: IconButton, icon: _jsx(Plus, {}), variant: "ghost", cursor: "pointer", size: "xs", fontSize: "md", "aria-label": "add-button", color: "#747474" }), _jsx(MenuList, Object.assign({ zIndex: 1000 }, { children: actionOptions.map((action) => pageID !== "register" && action === "back_to_login" ? null : (_jsx(MenuItem, Object.assign({ value: action, icon: _jsx(Center, { children: _jsx(Icon, { as: ActionPropertyBuildersMap[action].icon, fontSize: "16px" }) }), onClick: (e) => handleActionAddType(e, type) }, { children: humanize(action) }), action))) }))] }))] }), _jsx(DragDropContext, Object.assign({ onDragEnd: (result) => onDragEnd(result, type) }, { children: _jsx(Droppable, Object.assign({ droppableId: "action-components", direction: "vertical" }, { children: (provided) => (_jsxs(Box, Object.assign({}, provided.droppableProps, { ref: provided.innerRef }, { children: [actions.length === 1 ? (_jsxs(HStack, Object.assign({ backgroundColor: "gray.100", padding: "12px", spacing: "14px", borderRadius: "4px" }, { children: [_jsx(Lightning, { color: "#CCCCCC", fontSize: "xl" }), _jsx(Text, Object.assign({ color: "#A2A2A2" }, { children: "No action" }))] }))) : (actions.slice(1).map((action, index) => (_jsx(Draggable, Object.assign({ draggableId: action.id, index: index + 1 }, { children: (provided) => (_jsx(Box, Object.assign({ ref: provided.innerRef }, provided.draggableProps, { children: _jsxs(HStack, Object.assign({ _hover: { backgroundColor: "gray.50" }, paddingRight: "10px", paddingLeft: "2px", borderRadius: "4px", cursor: "pointer" }, { children: [_jsx(Center, Object.assign({}, provided.dragHandleProps, { children: _jsx(Icon, { color: "gray.400", fontSize: "md", as: Drag }) })), _jsxs(HStack, Object.assign({ flex: 1, paddingY: "10px", spacing: "14px", onClick: (e) => {
                                                    e.stopPropagation();
                                                    handleMoveToDrawerAction(action.id);
                                                } }, { children: [_jsx(Center, Object.assign({ backgroundColor: "#E6F0FF", padding: "8px", borderRadius: "4px" }, { children: _jsx(Icon, { as: ActionPropertyBuildersMap[action.type].icon, color: "#4D93FF", fontSize: "xl" }) })), _jsxs(VStack, Object.assign({ spacing: 0 }, { children: [_jsx(Text, Object.assign({ fontWeight: "600" }, { children: humanize(action.type) })), _jsx(Text, Object.assign({ color: "#A2A2A2" }, { children: humanize(action.type) }))] }))] })), _jsx(Icon, { as: Close, zIndex: 100, onClick: () => handleRemoveAction(action.id, type), _hover: { color: "#747474" }, color: "#CCCCCC", fontSize: "md" })] })) }))) }), action.id)))), provided.placeholder] }))) })) }))] }));
};
const ActionPropertyButton = (props) => {
    const pages = RuntimeContext.useSelectState((state) => state.maps.page);
    const pageID = usePageParam();
    const runtimeActions = RuntimeContext.useActions();
    const pageIDs = React.useMemo(() => new Set(Object.keys(pages)), [pages]);
    const componentRef = React.useRef();
    const actionOptions = React.useMemo(() => Object.keys(ActionPropertyBuildersMap).filter((action) => action !== "none"), [ActionPropertyBuildersMap]);
    const [actionID, setActionID] = React.useState();
    const actionValues = React.useMemo(() => {
        const actionData = _.cloneDeep(props.value);
        const values = Array.isArray(actionData)
            ? actionData.map((action) => !action.id ? Object.assign(Object.assign({}, action), { id: nanoid(3) }) : action)
            : actionData.type === "none"
                ? [
                    Object.assign(Object.assign({}, actionData), { onError: [{ type: "none" }], id: "1" }),
                ]
                : [
                    {
                        id: "1",
                        type: "none",
                        onError: [{ type: "none" }],
                    },
                    Object.assign(Object.assign({}, actionData), (!actionData.id && { id: "2" })),
                ];
        return values;
    }, [props.value]);
    const onErrorActions = React.useMemo(() => {
        return actionValues[0].type === "none" && actionValues[0].onError
            ? actionValues[0].onError.map((action) => !action.id ? Object.assign(Object.assign({}, action), { id: nanoid(3) }) : action)
            : [{ type: "none" }];
    }, [actionValues, props.value]);
    const selectedAction = React.useMemo(() => {
        return (actionValues.find((value) => value.id === actionID) ||
            onErrorActions.find((value) => value.id === actionID));
    }, [actionValues, actionID, onErrorActions]);
    const selectedActionVariables = React.useMemo(() => {
        if (!selectedAction)
            return [];
        const index = actionValues.findIndex((value) => value.id === selectedAction.id);
        if (index !== -1)
            return actionValues
                .slice(0, index)
                .reduce((variables, action) => _.union(variables, ActionPropertyBuildersMap[action.type].provides || []), []);
        const errorIndex = onErrorActions.findIndex((value) => value.id === selectedAction.id);
        return onErrorActions
            .slice(0, errorIndex)
            .reduce((variables, action) => _.union(variables, ActionPropertyBuildersMap[action.type].provides || []), []);
    }, [selectedAction, actionValues, onErrorActions]);
    const reassignActionOnError = React.useCallback((updatedActions) => actionValues.map((action) => action.type === "none" ? Object.assign(Object.assign({}, action), { onError: updatedActions }) : action), [actionValues]);
    const drawerOnSuccessActionDisclosure = useDisclosure();
    const drawerOnErrorActionDisclosure = useDisclosure();
    const drawerActionDisclosure = drawerOnSuccessActionDisclosure.isOpen
        ? drawerOnSuccessActionDisclosure
        : drawerOnErrorActionDisclosure;
    const handleActionAddType = React.useCallback((e, key) => {
        var _a, _b;
        const nextAction = Object.assign(Object.assign({}, actionTypeDefaultValues[e.currentTarget.value]), { id: nanoid(3) });
        if (nextAction.type === "view_detail" &&
            !pageIDs.has(nextAction.pageID)) {
            runtimeActions.addPage(Object.assign(Object.assign({}, initialPage), { id: nextAction.pageID, title: "Detail page", sourceID: (_a = props.view) === null || _a === void 0 ? void 0 : _a.name }));
        }
        if (nextAction.type === "request_recover_account" &&
            !pageIDs.has(nextAction.redirectPage)) {
            runtimeActions.addPage(Object.assign(Object.assign({}, initialPage), { id: nextAction.redirectPage, title: "Recover Account", sourceID: (_b = props.view) === null || _b === void 0 ? void 0 : _b.name, params: {
                    token: "",
                } }));
            const passwordComponent = buildComponent("Password");
            runtimeActions.addComponent(Object.assign(Object.assign({}, passwordComponent), { properties: Object.assign(Object.assign({}, passwordComponent.properties), { label: "New Password", placeholder: "Enter new password", confirmPassword: true, confirmLabel: "Confirm New Password", confirmPlaceholder: "Enter new password", data: {
                        inputID: "password",
                        type: "custom",
                        field: { type: "string", options: { format: "text" } },
                        validation: {
                            required: true,
                        },
                    } }) }), {
                page: nextAction.redirectPage,
            });
            const buttonComponent = buildComponent("Button");
            runtimeActions.addComponent(Object.assign(Object.assign({}, buttonComponent), { properties: Object.assign(Object.assign({}, buttonComponent.properties), { label: "Recover", action: [
                        { type: "none" },
                        {
                            id: nanoid(3),
                            type: "recover_account",
                            token: "@[params.token](params.token)",
                            password: "@[input.password](input.password)",
                        },
                    ] }) }), {
                page: nextAction.redirectPage,
            });
        }
        if (key === "onSuccess") {
            props.onChange([...actionValues, nextAction]);
        }
        else if (key === "onError") {
            const onError = reassignActionOnError([...onErrorActions, nextAction]);
            props.onChange(onError);
        }
    }, [
        props.onChange,
        pageIDs,
        props.view,
        actionValues,
        onErrorActions,
        reassignActionOnError,
    ]);
    const handleActionChange = React.useCallback((action) => {
        let updatedActions;
        if (drawerOnSuccessActionDisclosure.isOpen) {
            updatedActions = actionValues.map((item) => item.id === action.id ? action : item);
        }
        else if (drawerOnErrorActionDisclosure.isOpen) {
            const updatedErrorAction = onErrorActions.map((item) => item.id === action.id ? action : item);
            updatedActions = reassignActionOnError(updatedErrorAction);
        }
        props.onChange(updatedActions);
    }, [
        props.onChange,
        actionValues,
        onErrorActions,
        drawerOnErrorActionDisclosure.isOpen,
        drawerOnSuccessActionDisclosure.isOpen,
    ]);
    const handleRemoveAction = React.useCallback((id, key) => {
        let deletedActions;
        if (key === "onSuccess") {
            deletedActions = actionValues.filter((action) => action.id !== id);
            if (deletedActions.length === 1 &&
                deletedActions[0].type === "none" &&
                deletedActions[0].onError)
                deletedActions[0].onError = [{ type: "none" }];
        }
        else if (key === "onError") {
            const deletedErrorAction = onErrorActions.filter((action) => action.id !== id);
            deletedActions = reassignActionOnError(deletedErrorAction);
        }
        props.onChange(deletedActions);
    }, [actionValues, onErrorActions, drawerOnSuccessActionDisclosure.isOpen]);
    const onDragEnd = React.useCallback((result, key) => {
        if (!result.destination)
            return;
        let updatedActions;
        const actions = _.cloneDeep(key === "onError" ? onErrorActions : actionValues);
        actions.splice(result.source.index, 1);
        if (key === "onSuccess") {
            actions.splice(result.destination.index, 0, actionValues[result.source.index]);
            updatedActions = actions;
        }
        else if (key === "onError") {
            const existingAction = onErrorActions[result.source.index];
            actions.splice(result.destination.index, 0, existingAction);
            updatedActions = reassignActionOnError(actions);
        }
        props.onChange(updatedActions);
    }, [actionValues, onErrorActions]);
    const handleMoveToDrawerAction = React.useCallback((key, id) => {
        key === "onSuccess"
            ? drawerOnSuccessActionDisclosure.onOpen()
            : drawerOnErrorActionDisclosure.onOpen();
        setActionID(id);
    }, [drawerOnSuccessActionDisclosure, drawerOnErrorActionDisclosure]);
    return (_jsxs(VStack, Object.assign({ width: "100%", ref: componentRef }, { children: [_jsxs(VStack, Object.assign({ width: "100%", alignItems: "normal", bgColor: "white", border: "1px solid #E7E7E7", borderRadius: "4px", padding: "8px", spacing: "8px" }, { children: [_jsx(ActionComponent, Object.assign({ type: "onSuccess", handleMoveToDrawerAction: (id) => handleMoveToDrawerAction("onSuccess", id), actionOptions: actionOptions, actions: actionValues, handleActionAddType: handleActionAddType, handleRemoveAction: handleRemoveAction, onDragEnd: onDragEnd, pageID: pageID }, { children: _jsxs(HStack, { children: [_jsx(Text, { children: props.propDef.label
                                        ? props.propDef.label
                                        : humanize(props.propName || "Select Action") }), !!props.propDef.description && (_jsx(Tooltip, Object.assign({ hasArrow: true, label: props.propDef.description }, { children: _jsx("span", { children: _jsx(Icon, { fontSize: "md", as: Information }) }) })))] }) })), actionValues.length > 1 && (_jsx(ActionComponent, Object.assign({ type: "onError", handleMoveToDrawerAction: (id) => handleMoveToDrawerAction("onError", id), actionOptions: actionOptions, actions: onErrorActions, handleActionAddType: handleActionAddType, handleRemoveAction: handleRemoveAction, onDragEnd: onDragEnd, pageID: pageID }, { children: _jsx(Text, { children: "On Error" }) })))] })), drawerActionDisclosure.isOpen && (_jsx(DrawerActionSettings, { drawerDisclosure: drawerActionDisclosure, handleActionChange: handleActionChange, pageID: pageID, selectedAction: selectedAction, variables: selectedActionVariables }))] })));
};
export default React.memo(ActionPropertyButton);
//# sourceMappingURL=action.js.map