import { jsx, jsxs } from "react/jsx-runtime";
import { useEffect, useMemo, useRef } from "react";
import { useField, useFieldSchema } from "@tachybase/schema";
import { DragOutlined, MenuOutlined, PlusOutlined } from "@ant-design/icons";
import { Space } from "antd";
import classnames from "classnames";
import { useTranslation } from "react-i18next";
import { SchemaToolbarProvider, useSchemaInitializerRender, useSchemaSettingsRender } from "../application/index.mjs";
import { useDataSourceManager } from "../data-source/data-source/DataSourceManagerProvider.mjs";
import { useDataSource } from "../data-source/data-source/DataSourceProvider.mjs";
import { DragHandler, useCompile, useDesignable, useGridContext, useGridRowContext } from "../schema-component/index.mjs";
import { gridRowColWrap } from "../schema-initializer/utils.mjs";
import { useGetAriaLabelOfDesigner } from "./hooks/useGetAriaLabelOfDesigner.mjs";
import { SchemaSettingsDropdown } from "./SchemaSettings.mjs";
import { useStyles } from "./styles.mjs";
const GeneralSchemaDesigner = (props)=>{
    var _rowCtx_cols, _ctx_renderSchemaInitializer;
    const { disableInitializer, title, template, schemaSettings, contextValue, draggable = true, showDataSource = true, AddMenuModalComponent } = props;
    const { dn, designable } = useDesignable();
    const field = useField();
    const { t } = useTranslation();
    const fieldSchema = useFieldSchema();
    const compile = useCompile();
    const { getAriaLabel } = useGetAriaLabelOfDesigner();
    const schemaSettingsProps = {
        dn,
        field,
        fieldSchema
    };
    const { render: schemaSettingsRender, exists: schemaSettingsExists } = useSchemaSettingsRender(fieldSchema['x-settings'] || schemaSettings, fieldSchema['x-settings-props']);
    const rowCtx = useGridRowContext();
    const ctx = useGridContext();
    const { styles } = useStyles();
    const dm = useDataSourceManager();
    const dataSources = null == dm ? void 0 : dm.getDataSources();
    const dataSourceContext = useDataSource();
    const dataSource = (null == dataSources ? void 0 : dataSources.length) > 1 && dataSourceContext;
    const templateName = [
        'FormItem',
        'ReadPrettyFormItem'
    ].includes(null == template ? void 0 : template.componentName) ? "".concat(null == template ? void 0 : template.name, " ").concat(t('(Fields only)')) : null == template ? void 0 : template.name;
    const initializerProps = useMemo(()=>{
        var _rowCtx_cols;
        return {
            insertPosition: 'afterEnd',
            wrap: (null == rowCtx ? void 0 : null == (_rowCtx_cols = rowCtx.cols) ? void 0 : _rowCtx_cols.length) > 1 ? void 0 : gridRowColWrap,
            Component: (props)=>/*#__PURE__*/ jsx(PlusOutlined, {
                    ...props,
                    role: "button",
                    "aria-label": getAriaLabel('schema-initializer'),
                    style: {
                        cursor: 'pointer',
                        fontSize: 14
                    }
                })
        };
    }, [
        getAriaLabel,
        null == rowCtx ? void 0 : null == (_rowCtx_cols = rowCtx.cols) ? void 0 : _rowCtx_cols.length
    ]);
    if (!designable) return null;
    return /*#__PURE__*/ jsx(SchemaToolbarProvider, {
        ...contextValue,
        children: /*#__PURE__*/ jsxs("div", {
            className: classnames('general-schema-designer', styles.overrideAntdCSS),
            children: [
                title && /*#__PURE__*/ jsx("div", {
                    className: classnames('general-schema-designer-title', styles.titleCss),
                    children: /*#__PURE__*/ jsxs(Space, {
                        size: 2,
                        children: [
                            /*#__PURE__*/ jsx("span", {
                                className: 'title-tag',
                                children: showDataSource && dataSource ? "".concat(compile(null == dataSource ? void 0 : dataSource.displayName), " > ").concat(compile(title)) : compile(title)
                            }),
                            template && /*#__PURE__*/ jsxs("span", {
                                className: 'title-tag',
                                children: [
                                    t('Reference template'),
                                    ": ",
                                    templateName || t('Untitled')
                                ]
                            })
                        ]
                    })
                }),
                /*#__PURE__*/ jsx("div", {
                    className: 'general-schema-designer-icons',
                    children: /*#__PURE__*/ jsxs(Space, {
                        size: 3,
                        align: 'center',
                        children: [
                            !!AddMenuModalComponent && /*#__PURE__*/ jsx(SchemaSettingsDropdown, {
                                title: /*#__PURE__*/ jsx(PlusOutlined, {
                                    role: "button",
                                    "aria-label": getAriaLabel('add-menu')
                                }),
                                ...schemaSettingsProps,
                                children: AddMenuModalComponent
                            }),
                            draggable && /*#__PURE__*/ jsx(DragHandler, {
                                children: /*#__PURE__*/ jsx(DragOutlined, {
                                    role: "button",
                                    "aria-label": getAriaLabel('drag-handler')
                                })
                            }),
                            !disableInitializer && ((null == ctx ? void 0 : ctx.InitializerComponent) ? /*#__PURE__*/ jsx(ctx.InitializerComponent, {
                                ...initializerProps
                            }) : null == ctx ? void 0 : null == (_ctx_renderSchemaInitializer = ctx.renderSchemaInitializer) ? void 0 : _ctx_renderSchemaInitializer.call(ctx, initializerProps)),
                            schemaSettingsExists ? schemaSettingsRender(contextValue) : /*#__PURE__*/ jsx(SchemaSettingsDropdown, {
                                title: /*#__PURE__*/ jsx(MenuOutlined, {
                                    role: "button",
                                    "aria-label": getAriaLabel('schema-settings'),
                                    style: {
                                        cursor: 'pointer',
                                        fontSize: 12
                                    }
                                }),
                                ...schemaSettingsProps,
                                children: props.children
                            })
                        ]
                    })
                })
            ]
        })
    });
};
const InternalSchemaToolbar = (props)=>{
    var _rowCtx_cols;
    const { title, initializer, settings, showBackground, showBorder = true, draggable = true } = props;
    const { designable } = useDesignable();
    const fieldSchema = useFieldSchema();
    const compile = useCompile();
    const { styles } = useStyles();
    const { getAriaLabel } = useGetAriaLabelOfDesigner();
    const dm = useDataSourceManager();
    const dataSources = null == dm ? void 0 : dm.getDataSources();
    const dataSourceContext = useDataSource();
    const dataSource = (null == dataSources ? void 0 : dataSources.length) > 1 && dataSourceContext;
    const titleArr = useMemo(()=>{
        if (!title) return;
        if ('string' == typeof title) return [
            compile(title)
        ];
        if (Array.isArray(title)) return title.map((item)=>compile(item));
    }, [
        compile,
        title
    ]);
    const { render: schemaSettingsRender, exists: schemaSettingsExists } = useSchemaSettingsRender(fieldSchema['x-settings'] || settings, fieldSchema['x-settings-props']);
    const { render: schemaInitializerRender, exists: schemaInitializerExists } = useSchemaInitializerRender(fieldSchema['x-initializer'] || initializer, fieldSchema['x-initializer-props']);
    const rowCtx = useGridRowContext();
    const gridContext = useGridContext();
    const initializerProps = useMemo(()=>{
        var _rowCtx_cols;
        return {
            insertPosition: 'afterEnd',
            wrap: (null == rowCtx ? void 0 : null == (_rowCtx_cols = rowCtx.cols) ? void 0 : _rowCtx_cols.length) > 1 ? void 0 : gridRowColWrap,
            Component: (props)=>/*#__PURE__*/ jsx(PlusOutlined, {
                    ...props,
                    role: "button",
                    "aria-label": getAriaLabel('schema-initializer'),
                    style: {
                        cursor: 'pointer',
                        fontSize: 14
                    }
                })
        };
    }, [
        getAriaLabel,
        null == rowCtx ? void 0 : null == (_rowCtx_cols = rowCtx.cols) ? void 0 : _rowCtx_cols.length
    ]);
    const dragElement = useMemo(()=>{
        if (false === draggable) return null;
        return /*#__PURE__*/ jsx(DragHandler, {
            children: /*#__PURE__*/ jsx(DragOutlined, {
                role: "button",
                "aria-label": getAriaLabel('drag-handler')
            })
        });
    }, [
        draggable,
        getAriaLabel
    ]);
    const initializerElement = useMemo(()=>{
        if (false === initializer) return null;
        if ((null == gridContext ? void 0 : gridContext.InitializerComponent) || (null == gridContext ? void 0 : gridContext.renderSchemaInitializer)) {
            var _gridContext_renderSchemaInitializer;
            return (null == gridContext ? void 0 : gridContext.InitializerComponent) ? /*#__PURE__*/ jsx(gridContext.InitializerComponent, {
                ...initializerProps
            }) : null == (_gridContext_renderSchemaInitializer = gridContext.renderSchemaInitializer) ? void 0 : _gridContext_renderSchemaInitializer.call(gridContext, initializerProps);
        }
        if (!schemaInitializerExists) return null;
        return schemaInitializerRender(initializerProps);
    }, [
        gridContext,
        initializer,
        initializerProps,
        schemaInitializerExists,
        schemaInitializerRender
    ]);
    const settingsElement = useMemo(()=>false !== settings && schemaSettingsExists ? schemaSettingsRender() : null, [
        schemaSettingsExists,
        schemaSettingsRender,
        settings
    ]);
    const toolbarRef = useRef(null);
    useEffect(()=>{
        const toolbarElement = toolbarRef.current;
        const parentElement = null == toolbarElement ? void 0 : toolbarElement.parentElement;
        function show() {
            if (toolbarElement) toolbarElement.style.display = 'block';
        }
        function hide() {
            if (toolbarElement) toolbarElement.style.display = 'none';
        }
        if (parentElement) {
            const style = window.getComputedStyle(parentElement);
            if ('static' === style.position) parentElement.style.position = 'relative';
            parentElement.addEventListener('mouseenter', show);
            parentElement.addEventListener('mouseleave', hide);
        }
        return ()=>{
            if (parentElement) {
                parentElement.removeEventListener('mouseenter', show);
                parentElement.removeEventListener('mouseleave', hide);
            }
        };
    }, []);
    if (!designable) return null;
    return /*#__PURE__*/ jsxs("div", {
        ref: toolbarRef,
        className: styles.toolbar,
        style: {
            border: showBorder ? 'auto' : 0,
            background: showBackground ? 'auto' : 0
        },
        children: [
            titleArr && /*#__PURE__*/ jsx("div", {
                className: styles.toolbarTitle,
                children: /*#__PURE__*/ jsx(Space, {
                    size: 2,
                    children: titleArr.map((item)=>/*#__PURE__*/ jsx("span", {
                            className: styles.toolbarTitleTag,
                            children: dataSource ? "".concat(compile(null == dataSource ? void 0 : dataSource.displayName), " > ").concat(item) : item
                        }, item))
                })
            }),
            /*#__PURE__*/ jsx("div", {
                className: styles.toolbarIcons,
                children: /*#__PURE__*/ jsxs(Space, {
                    size: 3,
                    align: 'center',
                    children: [
                        dragElement,
                        initializerElement,
                        settingsElement
                    ]
                })
            })
        ]
    });
};
const SchemaToolbar = (props)=>{
    const { designable } = useDesignable();
    if (!designable) return null;
    return /*#__PURE__*/ jsx(InternalSchemaToolbar, {
        ...props
    });
};
export { GeneralSchemaDesigner, SchemaToolbar };
