import { jsx, jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useState } from "react";
import { RecursionField, observer, useField, useFieldSchema, useForm } from "@tachybase/schema";
import { isPortalInBody } from "@tego/client";
import { App, Button } from "antd";
import classnames from "classnames";
import lodash from "lodash";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import { StablePopover, useActionContext, useDesignable } from "../../index.mjs";
import { useApp } from "../../../application/index.mjs";
import { withDynamicSchemaProps } from "../../../application/hoc/withDynamicSchemaProps.mjs";
import { useACLActionParamsContext } from "../../../built-in/acl/index.mjs";
import { PathHandler } from "../../../built-in/dynamic-page/utils.mjs";
import { useCollection, useCollectionRecordData } from "../../../data-source/index.mjs";
import { Icon } from "../../../icon/index.mjs";
import { RecordProvider } from "../../../record-provider/index.mjs";
import { useLocalVariables, useVariables } from "../../../variables/index.mjs";
import { SortableItem } from "../../common/index.mjs";
import { useCompile, useComponent, useDesigner } from "../../hooks/index.mjs";
import { useProps } from "../../hooks/useProps.mjs";
import { ActionArea } from "./Action.Area.mjs";
import Action_Container from "./Action.Container.mjs";
import { ActionDesigner } from "./Action.Designer.mjs";
import { ActionDrawer } from "./Action.Drawer.mjs";
import { ActionLink } from "./Action.Link.mjs";
import { ActionModal } from "./Action.Modal.mjs";
import { ActionPage } from "./Action.Page.mjs";
import Action_style from "./Action.style.mjs";
import { ActionContextProvider } from "./context.mjs";
import { useA } from "./hooks.mjs";
import { useCompiledAction } from "./hooks/useCompiledAction.mjs";
import { useGetAriaLabelOfAction } from "./hooks/useGetAriaLabelOfAction.mjs";
import { linkageAction } from "./utils.mjs";
const Action = withDynamicSchemaProps(observer((props)=>{
    var _fieldSchema_xcomponentprops, _fieldSchema_xcomponentprops1, _field_data, _field_data1;
    const { isShow = true, popover, confirm, openMode: om, containerRefKey, component, useAction = useA, className, icon, title, onClick, style, openSize: os, disabled: propsDisabled, actionCallback, addChild, ...others } = useProps(props);
    const aclCtx = useACLActionParamsContext();
    const navigate = useNavigate();
    const { wrapSSR, componentCls, hashId } = Action_style();
    const { t } = useTranslation();
    const [visible, setVisible] = useState(false);
    const [formValueChanged, setFormValueChanged] = useState(false);
    const Designer = useDesigner();
    const field = useField();
    const app = useApp();
    const pageMode = app.usePageMode();
    const fieldSchema = useFieldSchema();
    const { run, element } = useCompiledAction(useAction, actionCallback);
    const form = useForm();
    const record = useCollectionRecordData();
    const collection = useCollection();
    const designerProps = fieldSchema['x-designer-props'];
    const openMode = null == fieldSchema ? void 0 : null == (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops['openMode'];
    const openSize = null == fieldSchema ? void 0 : null == (_fieldSchema_xcomponentprops1 = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops1['openSize'];
    const disabled = form.disabled || field.disabled || (null == (_field_data = field.data) ? void 0 : _field_data.disabled) || propsDisabled;
    const linkageRules = (null == fieldSchema ? void 0 : fieldSchema['x-linkage-rules']) || [];
    const { designable } = useDesignable();
    const tarComponent = useComponent(component) || component;
    const { modal } = App.useApp();
    const variables = useVariables();
    const localVariables = useLocalVariables({
        currentForm: {
            values: record
        }
    });
    const { getAriaLabel } = useGetAriaLabelOfAction(title);
    const compile = useCompile();
    let actionTitle = title || compile(fieldSchema.title);
    actionTitle = lodash.isString(actionTitle) ? t(actionTitle) : actionTitle;
    useEffect(()=>{
        field.stateOfLinkageRules = {};
        linkageRules.filter((k)=>!k.disabled).forEach((v)=>{
            var _v_actions;
            null == (_v_actions = v.actions) || _v_actions.forEach((h)=>{
                linkageAction({
                    operator: h.operator,
                    field,
                    condition: v.condition,
                    variables,
                    localVariables
                });
            });
        });
    }, [
        field,
        linkageRules,
        localVariables,
        record,
        variables
    ]);
    const handleButtonClick = useCallback((e)=>{
        if (isPortalInBody(e.target)) return;
        e.preventDefault();
        e.stopPropagation();
        if (!disabled && aclCtx) {
            const onOk = ()=>{
                null == onClick || onClick(e);
                const containerSchema = fieldSchema.reduceProperties((buf, s)=>'Action.Container' === s['x-component'] ? s : buf);
                if ((null == pageMode ? void 0 : pageMode.enable) && containerSchema) {
                    const target = PathHandler.getInstance().toWildcardPath({
                        collection: collection.name,
                        filterByTk: record[collection.getPrimaryKey()]
                    });
                    navigate('../' + containerSchema['x-uid'] + '/' + target);
                } else setVisible(true);
                run();
            };
            if (null == confirm ? void 0 : confirm.content) modal.confirm({
                title: t(confirm.title, {
                    title: actionTitle
                }),
                content: t(confirm.content, {
                    title: actionTitle
                }),
                onOk
            });
            else onOk();
        }
    }, [
        confirm,
        disabled,
        modal,
        onClick,
        run
    ]);
    const buttonStyle = useMemo(()=>{
        var _field_data;
        return {
            ...style,
            opacity: designable && ((null == field ? void 0 : null == (_field_data = field.data) ? void 0 : _field_data.hidden) || !aclCtx) && 0.1
        };
    }, [
        designable,
        null == field ? void 0 : null == (_field_data1 = field.data) ? void 0 : _field_data1.hidden,
        style
    ]);
    const renderButton = ()=>{
        var _field_data, _field_data1;
        if (!designable && ((null == field ? void 0 : null == (_field_data = field.data) ? void 0 : _field_data.hidden) || !aclCtx)) return null;
        return /*#__PURE__*/ jsxs(SortableItem, {
            role: "button",
            "aria-label": getAriaLabel(),
            ...others,
            loading: null == field ? void 0 : null == (_field_data1 = field.data) ? void 0 : _field_data1.loading,
            icon: icon ? /*#__PURE__*/ jsx(Icon, {
                type: icon
            }) : null,
            disabled: disabled,
            style: buttonStyle,
            onClick: handleButtonClick,
            component: tarComponent || Button,
            className: classnames(componentCls, hashId, className, 'tb-action'),
            type: 'danger' === props.type ? void 0 : props.type,
            children: [
                actionTitle,
                /*#__PURE__*/ jsx(Designer, {
                    ...designerProps
                })
            ]
        });
    };
    const result = /*#__PURE__*/ jsxs(ActionContextProvider, {
        button: renderButton(),
        visible: visible,
        setVisible: setVisible,
        formValueChanged: formValueChanged,
        setFormValueChanged: setFormValueChanged,
        openMode: openMode,
        openSize: openSize,
        containerRefKey: containerRefKey,
        fieldSchema: fieldSchema,
        children: [
            popover && /*#__PURE__*/ jsx(RecursionField, {
                basePath: field.address,
                onlyRenderProperties: true,
                schema: fieldSchema
            }),
            !popover && renderButton(),
            !popover && props.children,
            element
        ]
    });
    if (!isShow) return null;
    if (addChild) return wrapSSR(/*#__PURE__*/ jsx(RecordProvider, {
        record: null,
        parent: record,
        children: result
    }));
    return wrapSSR(result);
}), {
    displayName: 'Action'
});
Action.Popover = observer((props)=>{
    const { button, visible, setVisible } = useActionContext();
    return /*#__PURE__*/ jsx(StablePopover, {
        ...props,
        destroyTooltipOnHide: true,
        open: visible,
        onOpenChange: (visible)=>{
            setVisible(visible);
        },
        content: props.children,
        children: button
    });
}, {
    displayName: 'Action.Popover'
});
Action.Popover.Footer = observer((props)=>/*#__PURE__*/ jsx("div", {
        style: {
            display: 'flex',
            justifyContent: 'flex-end',
            width: '100%'
        },
        children: props.children
    }), {
    displayName: 'Action.Popover.Footer'
});
Action.Link = ActionLink;
Action.Designer = ActionDesigner;
Action.Drawer = ActionDrawer;
Action.Modal = ActionModal;
Action.Container = Action_Container;
Action.Page = ActionPage;
Action.Area = ActionArea;
const action_Action = Action;
export { Action, action_Action as default };
