import { jsx } from "react/jsx-runtime";
import { observer } from "@tachybase/schema";
import { DisconnectOutlined, LoadingOutlined } from "@ant-design/icons";
import { css as css_css } from "@emotion/css";
import { DotLottieReact } from "@lottiefiles/dotlottie-react";
import { getSubAppName } from "@tego/client";
import { Button, Result } from "antd";
import { createStyles } from "antd-style";
import { useTranslation } from "react-i18next";
import { Navigate } from "react-router-dom";
import { useAPIClient } from "../api-client/index.mjs";
import { NoticeLevel, useApp } from "../application/index.mjs";
import { Plugin } from "../application/Plugin.mjs";
import { PageLayout } from "../block-provider/PageLayout.mjs";
import { CollectionPlugin } from "../collection-manager/index.mjs";
import { RouteSchemaComponent } from "../route-switch/index.mjs";
import { AntdSchemaComponentPlugin, SchemaComponentPlugin } from "../schema-component/index.mjs";
import { ErrorFallback } from "../schema-component/antd/error-fallback/index.mjs";
import { AssociationFilterPlugin } from "../schema-initializer/index.mjs";
import { SchemaInitializerPlugin } from "../schema-initializer/SchemaInitializerPlugin.mjs";
import { SchemaSettingsPlugin } from "../schema-settings/index.mjs";
import { BlockTemplateDetails, BlockTemplatePage } from "../schema-templates/index.mjs";
import { CurrentUserProvider, CurrentUserSettingsMenuProvider } from "../user/index.mjs";
import { ACLPlugin } from "./acl/ACLPlugin.mjs";
import { AdminLayoutPlugin } from "./admin-layout/AdminLayoutPlugin.mjs";
import { WelcomeCard } from "./admin-layout/components/WelcomeCard.mjs";
import { AttachmentPreviewPlugin } from "./attachment-preview/index.mjs";
import { PluginBlockSchemaComponent } from "./block-schema-component/index.mjs";
import { PluginContextMenu } from "./context-menu/index.mjs";
import { RemoteDocumentTitlePlugin } from "./document-title/index.mjs";
import { PluginDynamicPage } from "./dynamic-page/index.mjs";
import { LocalePlugin } from "./locale/LocalePlugin.mjs";
import { PluginPageStyle } from "./page-style/index.mjs";
import { PluginPinnedList } from "./pinned-list/PluginPinnedList.mjs";
import { PMPlugin } from "./pm/index.mjs";
import { QuickAccessPlugin } from "./quick-access/index.mjs";
import { ScrollAssistantPlugin } from "./scroll-assistant/index.mjs";
import { SystemSettingsPlugin } from "./system-settings/index.mjs";
import { PluginSystemVersion } from "./system-version/index.mjs";
import { UserSettingsPlugin } from "./user-settings/index.mjs";
import { AdminLayout, AdminProvider, AdminTabs, MenuEditor, NoticeArea } from "./admin-layout/index.mjs";
export * from "./pinned-list/index.mjs";
export * from "./context-menu/useContextMenu.mjs";
function _tagged_template_literal(strings, raw) {
    if (!raw) raw = strings.slice(0);
    return Object.freeze(Object.defineProperties(strings, {
        raw: {
            value: Object.freeze(raw)
        }
    }));
}
function _templateObject() {
    const data = _tagged_template_literal([
        "\n        display: flex;\n        justify-content: center;\n        align-items: center;\n        width: 100vw;\n        height: 100vh;\n        background-color: #f5f5f5;\n        overflow: hidden;\n      "
    ]);
    _templateObject = function() {
        return data;
    };
    return data;
}
function _templateObject1() {
    const data = _tagged_template_literal([
        "\n      top: 50%;\n      position: absolute;\n      width: 100%;\n      transform: translate(0, -50%);\n    "
    ]);
    _templateObject1 = function() {
        return data;
    };
    return data;
}
const AppSpin = ()=>/*#__PURE__*/ jsx("div", {
        className: css_css(_templateObject()),
        children: /*#__PURE__*/ jsx(DotLottieReact, {
            style: {
                width: '100%',
                maxWidth: '640px'
            },
            src: "https://assets.tachybase.com/imgs/spin.lottie",
            loop: true,
            autoplay: true
        })
    });
const useStyles = createStyles((param)=>{
    let { css } = param;
    return {
        modal: css(_templateObject1())
    };
});
const useErrorProps = (app, error)=>{
    var _error_response_data_errors, _error_response_data, _error_response;
    const api = useAPIClient();
    if (!error) return {};
    const err = (null == error ? void 0 : null == (_error_response = error.response) ? void 0 : null == (_error_response_data = _error_response.data) ? void 0 : null == (_error_response_data_errors = _error_response_data.errors) ? void 0 : _error_response_data_errors[0]) || error;
    const subApp = getSubAppName(app.getPublicPath());
    switch(err.code){
        case 'USER_HAS_NO_ROLES_ERR':
            return {
                title: app.i18n.t('Permission denied'),
                subTitle: err.message,
                extra: [
                    /*#__PURE__*/ jsx(Button, {
                        type: "primary",
                        onClick: ()=>{
                            api.auth.setToken(null);
                            window.location.reload();
                        },
                        children: app.i18n.t('Sign in with another account')
                    }, "try"),
                    subApp ? /*#__PURE__*/ jsx(Button, {
                        onClick: ()=>window.location.href = '/admin',
                        children: app.i18n.t('Return to the main application')
                    }, "back") : null
                ]
            };
        default:
            return {};
    }
};
const AppError = observer((param)=>{
    let { app, error } = param;
    const props = useErrorProps(app, error);
    const { styles } = useStyles();
    return /*#__PURE__*/ jsx("div", {
        children: /*#__PURE__*/ jsx(Result, {
            className: styles.modal,
            status: "error",
            title: app.i18n.t('App error'),
            subTitle: app.i18n.t(null == error ? void 0 : error.message),
            extra: [
                /*#__PURE__*/ jsx(Button, {
                    type: "primary",
                    onClick: ()=>window.location.reload(),
                    children: app.i18n.t('Try again')
                }, "try")
            ],
            ...props
        })
    });
}, {
    displayName: 'AppError'
});
const getProps = (app)=>{
    if (app.ws.serverDown) return {
        status: 'error',
        icon: /*#__PURE__*/ jsx(DisconnectOutlined, {}),
        title: "You're offline",
        subTitle: 'Please check the server status or network connection status'
    };
    if (!app.error) return {};
    if ('APP_NOT_FOUND' === app.error.code) {
        var _app_error;
        return {
            status: 'warning',
            title: 'App not found',
            subTitle: null == (_app_error = app.error) ? void 0 : _app_error.message
        };
    }
    if ('APP_INITIALIZING' === app.error.code) {
        var _app_error1;
        return {
            status: 'info',
            icon: /*#__PURE__*/ jsx(LoadingOutlined, {}),
            title: 'App initializing',
            subTitle: null == (_app_error1 = app.error) ? void 0 : _app_error1.message
        };
    }
    if ('APP_INITIALIZED' === app.error.code) {
        var _app_error2;
        return {
            status: 'warning',
            title: 'App initialized',
            subTitle: null == (_app_error2 = app.error) ? void 0 : _app_error2.message
        };
    }
    if ('APP_ERROR' === app.error.code || 'LOAD_ERROR' === app.error.code) {
        var _app_error3;
        return {
            status: 'error',
            title: 'App error',
            subTitle: null == (_app_error3 = app.error) ? void 0 : _app_error3.message
        };
    }
    if ('APP_NOT_INSTALLED_ERROR' === app.error.code) {
        var _app_error4;
        return {
            status: 'warning',
            title: 'App not installed',
            subTitle: null == (_app_error4 = app.error) ? void 0 : _app_error4.message
        };
    }
    if ('APP_STOPPED' === app.error.code) {
        var _app_error5;
        return {
            status: 'warning',
            title: 'App stopped',
            subTitle: null == (_app_error5 = app.error) ? void 0 : _app_error5.message
        };
    }
    if ('APP_COMMANDING' === app.error.code) {
        var _app_error_command, _app_error6, _app_error7, _app_error_command1, _app_error8;
        const props = {
            status: 'info',
            icon: /*#__PURE__*/ jsx(LoadingOutlined, {}),
            title: null == (_app_error6 = app.error) ? void 0 : null == (_app_error_command = _app_error6.command) ? void 0 : _app_error_command.name,
            subTitle: null == (_app_error7 = app.error) ? void 0 : _app_error7.message
        };
        const commands = {
            start: {
                title: 'App starting'
            },
            restart: {
                title: 'App restarting'
            },
            install: {
                title: 'App installing'
            },
            upgrade: {
                title: 'App upgrading'
            },
            'pm.add': {
                title: 'Adding plugin'
            },
            'pm.update': {
                title: 'Updating plugin'
            },
            'pm.enable': {
                title: 'Enabling plugin'
            },
            'pm.disable': {
                title: 'Disabling plugin'
            },
            'pm.remove': {
                title: 'Removing plugin'
            },
            refreshEventSource: {
                title: 'Refreshing event source'
            }
        };
        return {
            ...props,
            ...commands[null == (_app_error8 = app.error) ? void 0 : null == (_app_error_command1 = _app_error8.command) ? void 0 : _app_error_command1.name]
        };
    }
    return {};
};
const AppMaintaining = observer((param)=>{
    let { app } = param;
    const { icon, status, title, subTitle } = getProps(app);
    const { styles } = useStyles();
    return /*#__PURE__*/ jsx("div", {
        children: /*#__PURE__*/ jsx(Result, {
            className: styles.modal,
            icon: icon,
            status: status,
            title: app.i18n.t(title),
            subTitle: app.i18n.t(subTitle)
        })
    });
}, {
    displayName: 'AppMaintaining'
});
const AppMaintainingDialog = observer((param)=>{
    let { app } = param;
    const { icon, status, title, subTitle } = getProps(app);
    const manager = app.noticeManager;
    manager.status(app.i18n.t(title) + ' ' + app.i18n.t(subTitle), NoticeLevel.INFO);
    return null;
}, {
    displayName: 'AppMaintainingDialog'
});
const AppNotFound = ()=>{
    const { t } = useTranslation();
    const app = useApp();
    return /*#__PURE__*/ jsx(Result, {
        status: "404",
        title: "404",
        subTitle: t('Sorry, the page you visited does not exist.'),
        extra: /*#__PURE__*/ jsx(Button, {
            onClick: ()=>location.href = app.adminUrl,
            type: "primary",
            children: t('Back Home')
        })
    });
};
class BuiltInPlugin extends Plugin {
    async afterAdd() {
        this.app.addComponents({
            AppSpin,
            AppError,
            AppMaintaining,
            AppMaintainingDialog,
            AppNotFound
        });
        await this.addPlugins();
    }
    async load() {
        this.addComponents();
        this.addRoutes();
        this.app.use(CurrentUserProvider);
        this.app.use(CurrentUserSettingsMenuProvider);
        this.addSystemSettingGroups();
    }
    addSystemSettingGroups() {
        this.app.systemSettingsManager.add('id-auth', {
            title: this.t('Identity and Authentication'),
            icon: 'UserOutlined',
            sort: -50
        });
        this.app.systemSettingsManager.add('data-modeling', {
            title: this.t('Data Modeling'),
            icon: 'DatabaseOutlined',
            sort: -40
        });
        this.app.systemSettingsManager.add('business-components', {
            title: this.t('Business Components'),
            icon: 'BlockOutlined',
            sort: -30
        });
        this.app.systemSettingsManager.add('security', {
            title: this.t('Security'),
            icon: 'SafetyOutlined',
            sort: -20
        });
        this.app.systemSettingsManager.add('system-services', {
            title: this.t('System Services'),
            icon: 'CloudServerOutlined',
            sort: -10
        });
    }
    addRoutes() {
        this.router.add('root', {
            path: '/',
            element: /*#__PURE__*/ jsx(Navigate, {
                replace: true,
                to: "/admin"
            })
        });
        this.router.add('not-found', {
            path: '*',
            Component: AppNotFound
        });
        this.router.add('app', {
            path: '/:entry',
            Component: 'AdminLayout'
        });
        this.router.add('app.page', {
            path: '/:entry/:name',
            Component: 'RouteSchemaComponent'
        });
        this.router.add('app.welcome', {
            path: '/:entry/welcome',
            Component: 'WelcomeCard'
        });
    }
    addComponents() {
        this.app.addComponents({
            ErrorFallback: ErrorFallback,
            RouteSchemaComponent: RouteSchemaComponent,
            BlockTemplatePage: BlockTemplatePage,
            BlockTemplateDetails: BlockTemplateDetails,
            WelcomeCard: WelcomeCard,
            PageLayout: PageLayout
        });
    }
    async addPlugins() {
        await this.app.pm.add(AssociationFilterPlugin);
        await this.app.pm.add(LocalePlugin, {
            name: 'builtin-locale'
        });
        await this.app.pm.add(AdminLayoutPlugin, {
            name: 'admin-layout'
        });
        await this.app.pm.add(SystemSettingsPlugin, {
            name: 'system-setting'
        });
        await this.app.pm.add(PluginPinnedList, {
            name: 'pinned-list',
            config: {
                items: {
                    ui: {
                        order: 50,
                        component: 'DesignableSwitch',
                        pin: true,
                        snippet: 'ui.*',
                        belongTo: 'pinnedmenu'
                    },
                    wf: {
                        order: 100,
                        component: 'WorkflowLink',
                        pin: true,
                        snippet: 'pm.*',
                        belongTo: 'pinnedmenu'
                    },
                    ds: {
                        order: 200,
                        component: 'DatasourceLink',
                        pin: true,
                        snippet: 'pm.*',
                        belongTo: 'pinnedmenu'
                    },
                    sc: {
                        order: 400,
                        component: 'SettingsCenterDropdown',
                        pin: true,
                        snippet: 'pm.*',
                        isPublic: true,
                        belongTo: 'pinnedmenu'
                    },
                    ca: {
                        order: 300,
                        component: 'CalculatorButton',
                        pin: true,
                        isPublic: true,
                        belongTo: 'hoverbutton'
                    },
                    cm: {
                        order: 90,
                        component: 'ContextMenuButton',
                        pin: true,
                        isPublic: true,
                        belongTo: 'hoverbutton'
                    },
                    db: {
                        order: 60,
                        component: 'DesignableButton',
                        pin: true,
                        snippet: 'ui.*',
                        belongTo: 'hoverbutton'
                    },
                    saj: {
                        order: 30,
                        component: 'SearchAndJumpButton',
                        pin: true,
                        snippet: 'pm.*',
                        belongTo: 'hoverbutton'
                    },
                    ai: {
                        order: 330,
                        component: 'AIChatButton',
                        pin: true,
                        isPublic: true,
                        belongTo: 'hoverbutton'
                    }
                }
            }
        });
        await this.app.pm.add(SchemaComponentPlugin, {
            name: 'schema-component'
        });
        await this.app.pm.add(SchemaInitializerPlugin, {
            name: 'schema-initializer'
        });
        await this.app.pm.add(SchemaSettingsPlugin, {
            name: 'schema-settings'
        });
        await this.app.pm.add(PluginBlockSchemaComponent, {
            name: 'block-schema-component'
        });
        await this.app.pm.add(AntdSchemaComponentPlugin, {
            name: 'antd-schema-component'
        });
        await this.app.pm.add(ACLPlugin, {
            name: 'builtin-acl'
        });
        await this.app.pm.add(RemoteDocumentTitlePlugin, {
            name: 'remote-document-title'
        });
        await this.app.pm.add(PMPlugin, {
            name: 'builtin-pm'
        });
        await this.app.pm.add(CollectionPlugin, {
            name: 'builtin-collection'
        });
        await this.app.pm.add(PluginContextMenu, {
            name: 'context-menu'
        });
        await this.app.pm.add(UserSettingsPlugin, {
            name: 'user-settings'
        });
        await this.app.pm.add(AttachmentPreviewPlugin, {
            name: 'attachment-preview'
        });
        await this.app.pm.add(PluginPageStyle, {
            name: 'page-style'
        });
        await this.app.pm.add(QuickAccessPlugin, {
            name: 'quick-access'
        });
        await this.app.pm.add(ScrollAssistantPlugin, {
            name: 'scroll-assistant'
        });
        await this.app.pm.add(PluginDynamicPage, {
            name: 'dynamic-page'
        });
        await this.app.pm.add(PluginSystemVersion, {
            name: 'system-version'
        });
    }
}
export { AdminLayout, AdminProvider, AdminTabs, AppNotFound, BuiltInPlugin, MenuEditor, NoticeArea };
