import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useContext, useEffect, useMemo, useState } from "react";
import { Schema, SchemaOptionsContext, useFieldSchema } from "@tachybase/schema";
import { PlusOutlined } from "@ant-design/icons";
import { PageHeader } from "@ant-design/pro-layout";
import { PointerSensor, useSensor, useSensors } from "@dnd-kit/core";
import { FormLayout } from "@tego/client";
import { Button, Tabs } from "antd";
import { cx } from "antd-style";
import classnames from "classnames";
import { ErrorBoundary } from "react-error-boundary";
import { useTranslation } from "react-i18next";
import { useSearchParams } from "react-router-dom";
import { FormDialog, PageExtendComponentProvider, ScrollArea } from "../index.mjs";
import { useToken } from "../__builtins__/index.mjs";
import { useStyles } from "../../../built-in/acl/style.mjs";
import { useContextMenu } from "../../../built-in/context-menu/useContextMenu.mjs";
import { useDocumentTitle } from "../../../built-in/document-title/index.mjs";
import { FilterBlockProvider } from "../../../filter-provider/FilterProvider.mjs";
import { Icon } from "../../../icon/index.mjs";
import { useGetAriaLabelOfSchemaInitializer } from "../../../schema-initializer/hooks/useGetAriaLabelOfSchemaInitializer.mjs";
import { useGlobalTheme } from "../../../style/theme/index.mjs";
import { DndContext } from "../../common/index.mjs";
import { SortableItem } from "../../common/sortable-item/index.mjs";
import { DragHandlePageTab } from "../../common/sortable-item/DragHandlePageTab.mjs";
import { SchemaComponent, SchemaComponentOptions } from "../../core/index.mjs";
import { useCompile, useDesignable } from "../../hooks/index.mjs";
import { ErrorFallback } from "../error-fallback/index.mjs";
import FixedBlock from "./FixedBlock.mjs";
import { useStyles as external_Page_style_mjs_useStyles } from "./Page.style.mjs";
import { PageDesigner } from "./PageDesigner.mjs";
import { PageTabDesigner } from "./PageTabDesigner.mjs";
import { getStyles } from "./style.mjs";
const Page = (props)=>{
    var _fieldSchema_xcomponentprops, _fieldSchema_xcomponentprops1, _fieldSchema_xcomponentprops2;
    const { children, ...others } = props;
    const { t } = useTranslation();
    const { title, setTitle } = useDocumentTitle();
    const fieldSchema = useFieldSchema();
    const disablePageHeader = null == (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops.disablePageHeader;
    const enablePageTabs = null == (_fieldSchema_xcomponentprops1 = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops1.enablePageTabs;
    const enableSharePage = null == (_fieldSchema_xcomponentprops2 = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops2.enableSharePage;
    const [searchParams, setSearchParams] = useSearchParams();
    const [loading, setLoading] = useState(false);
    const activeKey = useMemo(()=>searchParams.get('tab') || Object.keys(fieldSchema.properties || {}).shift(), [
        fieldSchema.properties,
        searchParams
    ]);
    const [height, setHeight] = useState(0);
    const aclStyles = useStyles();
    const { wrapSSR, hashId, componentCls } = getStyles();
    useEffect(()=>{
        if (!title) setTitle(t(fieldSchema.title));
    }, [
        fieldSchema.title,
        title
    ]);
    return wrapSSR(/*#__PURE__*/ jsx(FilterBlockProvider, {
        children: /*#__PURE__*/ jsxs("div", {
            className: "".concat(componentCls, " ").concat(hashId, " ").concat(aclStyles.styles),
            children: [
                /*#__PURE__*/ jsx(PageDesigner, {
                    title: fieldSchema.title || title
                }),
                /*#__PURE__*/ jsx(Page_PageHeader, {
                    disablePageHeader: disablePageHeader,
                    enablePageTabs: enablePageTabs,
                    activeKey: activeKey,
                    title: title,
                    fieldSchema: fieldSchema,
                    parentProps: others,
                    setHeight: setHeight,
                    setLoading: setLoading,
                    enableSharePage: enableSharePage,
                    setSearchParams: setSearchParams
                }),
                /*#__PURE__*/ jsx(PageContentComponent, {
                    loading: loading,
                    disablePageHeader: disablePageHeader,
                    enablePageTabs: enablePageTabs,
                    fieldSchema: fieldSchema,
                    activeKey: activeKey,
                    height: height,
                    children: children
                })
            ]
        })
    }));
};
const Page_PageHeader = (props)=>{
    var _fieldSchema_xcomponentprops, _Object_values, _Object_values1;
    const { disablePageHeader, enablePageTabs, setHeight, activeKey, setLoading, setSearchParams, fieldSchema, title, parentProps, enableSharePage } = props;
    const { theme } = useGlobalTheme();
    const options = useContext(SchemaOptionsContext);
    const compile = useCompile();
    const { showScrollArea } = useContextMenu();
    const hidePageTitle = null == (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops.hidePageTitle;
    const extendComponents = fieldSchema['x-extend-components'] || {};
    const pageHeaderTitle = hidePageTitle ? void 0 : fieldSchema.title || compile(title);
    const items = fieldSchema.mapProperties((schema)=>({
            key: schema.name,
            label: /*#__PURE__*/ jsx(TabItem, {
                schema: schema
            })
        }));
    return /*#__PURE__*/ jsxs("div", {
        ref: (ref)=>{
            setHeight(Math.floor((null == ref ? void 0 : ref.getBoundingClientRect().height) || 0) + 1);
        },
        className: "tb-page-header-wrapper",
        children: [
            !disablePageHeader && /*#__PURE__*/ jsx(PageHeader, {
                className: classnames('pageHeaderCss', pageHeaderTitle || enableSharePage ? '' : 'height0'),
                ghost: false,
                title: pageHeaderTitle || ' ',
                ...parentProps,
                extra: /*#__PURE__*/ jsxs(Fragment, {
                    children: [
                        null == (_Object_values = Object.values(extendComponents)) ? void 0 : _Object_values.map((item, index)=>{
                            const schema = {
                                type: 'void',
                                name: item.name,
                                'x-component': item.component,
                                'x-component-props': {}
                            };
                            const componentProps = {
                                ...props,
                                isExtra: true,
                                fieldSchema
                            };
                            return /*#__PURE__*/ jsx(PageExtendComponentProvider, {
                                ...componentProps,
                                children: /*#__PURE__*/ jsx(SchemaComponent, {
                                    schema: schema
                                })
                            });
                        }),
                        !enablePageTabs && showScrollArea && /*#__PURE__*/ jsx(ScrollArea, {})
                    ]
                }),
                footer: enablePageTabs && /*#__PURE__*/ jsx(TabComponent, {
                    activeKey: activeKey,
                    setLoading: setLoading,
                    setSearchParams: setSearchParams,
                    showScrollArea: showScrollArea,
                    options: options,
                    theme: theme,
                    items: items
                })
            }),
            null == (_Object_values1 = Object.values(extendComponents)) ? void 0 : _Object_values1.map((item, index)=>{
                const schema = {
                    type: 'void',
                    name: 'icon' + item.name,
                    'x-component': item.component,
                    'x-component-props': {}
                };
                const componentProps = {
                    ...props,
                    fieldSchema
                };
                return /*#__PURE__*/ jsx(PageExtendComponentProvider, {
                    ...componentProps,
                    children: /*#__PURE__*/ jsx(SchemaComponent, {
                        schema: schema
                    })
                });
            })
        ]
    });
};
const TabComponent = (props)=>{
    const { activeKey, setLoading, setSearchParams, showScrollArea, options, theme, items } = props;
    const { styles } = external_Page_style_mjs_useStyles();
    const [hasMounted, setHasMounted] = useState(false);
    const sensors = useSensors(useSensor(PointerSensor, {
        activationConstraint: {
            distance: 5
        }
    }));
    const handleTabClick = (activeKey)=>{
        setLoading(true);
        setSearchParams([
            [
                'tab',
                activeKey
            ]
        ]);
        setTimeout(()=>{
            setLoading(false);
        }, 50);
    };
    useEffect(()=>{
        setTimeout(()=>{
            setHasMounted(true);
        });
    }, []);
    return /*#__PURE__*/ jsx(DndContext, {
        sensors: sensors,
        children: /*#__PURE__*/ jsx(Tabs, {
            className: styles.tabComponentClass,
            type: "card",
            size: 'small',
            animated: hasMounted,
            activeKey: activeKey,
            items: items,
            onTabClick: handleTabClick,
            tabBarExtraContent: /*#__PURE__*/ jsx(TabBarExtraContent, {
                theme: theme,
                showScrollArea: showScrollArea,
                options: options
            })
        })
    });
};
const TabItem = (props)=>{
    const { schema } = props;
    const { t } = useTranslation();
    const { styles } = external_Page_style_mjs_useStyles();
    return /*#__PURE__*/ jsx(SortableItem, {
        id: schema.name,
        schema: schema,
        className: classnames('tb-action-link', 'designerCss', props.className, styles.tabItemClass),
        children: /*#__PURE__*/ jsxs(DragHandlePageTab, {
            children: [
                schema['x-icon'] && /*#__PURE__*/ jsx(Icon, {
                    style: {
                        marginRight: 8
                    },
                    type: schema['x-icon']
                }),
                /*#__PURE__*/ jsx("span", {
                    children: schema.title || t('Unnamed')
                }),
                /*#__PURE__*/ jsx("div", {
                    className: "tab-designer-wrapper",
                    children: /*#__PURE__*/ jsx(PageTabDesigner, {
                        schema: schema
                    })
                })
            ]
        })
    });
};
const TabBarExtraContent = (props)=>{
    const { showScrollArea, options, theme } = props;
    const dn = useDesignable();
    const { t } = useTranslation();
    const { getAriaLabel } = useGetAriaLabelOfSchemaInitializer();
    const { styles } = external_Page_style_mjs_useStyles();
    const handleAddTab = async ()=>{
        const values = await FormDialog(t('Add tab'), ()=>/*#__PURE__*/ jsx(AddTabForm, {
                options: options
            }), theme).open({
            initialValues: {}
        });
        const { title, icon } = values;
        dn.insertBeforeEnd({
            type: 'void',
            title,
            'x-icon': icon,
            'x-component': 'Grid',
            'x-initializer': 'page:addBlock',
            properties: {}
        });
    };
    return /*#__PURE__*/ jsxs("div", {
        className: cx(styles.tabWrapper, {
            designable: dn.designable
        }),
        children: [
            dn.designable && /*#__PURE__*/ jsx(Button, {
                className: "add-tab-btn",
                type: "text",
                "aria-label": getAriaLabel('tabs'),
                icon: /*#__PURE__*/ jsx(PlusOutlined, {}),
                onClick: handleAddTab
            }),
            showScrollArea && /*#__PURE__*/ jsx(ScrollArea, {
                className: "scroll-area-extra-content"
            })
        ]
    });
};
const AddTabForm = (props)=>{
    const { options } = props;
    const { t } = useTranslation();
    return /*#__PURE__*/ jsx(SchemaComponentOptions, {
        scope: options.scope,
        components: {
            ...options.components
        },
        children: /*#__PURE__*/ jsx(FormLayout, {
            layout: 'vertical',
            children: /*#__PURE__*/ jsx(SchemaComponent, {
                schema: {
                    properties: {
                        title: {
                            title: t('Tab name'),
                            'x-component': 'Input',
                            'x-decorator': 'FormItem',
                            required: true
                        },
                        icon: {
                            title: t('Icon'),
                            'x-component': 'IconPicker',
                            'x-decorator': 'FormItem'
                        }
                    }
                }
            })
        })
    });
};
const PageContentComponent = (props)=>{
    const handleErrors = (error)=>{
        var _window_Sentry, _window;
        null == (_window = window) || null == (_window_Sentry = _window.Sentry) || _window_Sentry.captureException(error);
        console.error(error);
    };
    return /*#__PURE__*/ jsx("div", {
        className: "tb-page-wrapper",
        children: /*#__PURE__*/ jsx(ErrorBoundary, {
            FallbackComponent: ErrorFallback,
            onError: handleErrors,
            children: /*#__PURE__*/ jsx(PageContent, {
                ...props
            })
        })
    });
};
const PageContent = (props)=>{
    const { loading, disablePageHeader, enablePageTabs, fieldSchema, activeKey, height, children } = props;
    const { token } = useToken();
    if (loading) return;
    if (!disablePageHeader && enablePageTabs) return fieldSchema.mapProperties((schema)=>{
        if (schema.name !== activeKey) return null;
        return /*#__PURE__*/ jsx(FixedBlock, {
            height: "calc(".concat(height, "px + 46px + ").concat(token.marginLG, "px * 2)"),
            children: /*#__PURE__*/ jsx(SchemaComponent, {
                schema: new Schema({
                    properties: {
                        [schema.name]: schema
                    }
                })
            })
        }, schema.name);
    });
    return /*#__PURE__*/ jsx(FixedBlock, {
        height: "calc(".concat(height, "px + 46px + ").concat(token.marginLG, "px * 2)"),
        children: /*#__PURE__*/ jsx("div", {
            className: "pageWithFixedBlockCss tb-page-content",
            children: children
        })
    });
};
export { Page };
