import { jsx, jsxs } from "react/jsx-runtime";
import { createContext, useCallback, useContext, useMemo, useState } from "react";
import { createForm, observer, useField, useFieldSchema, useForm } from "@tachybase/schema";
import { flatten, unflatten } from "@tachybase/utils/client";
import { Button, Space } from "antd";
import { createStyles } from "antd-style";
import { useTranslation } from "react-i18next";
import { withDynamicSchemaProps } from "../../../application/hoc/withDynamicSchemaProps.mjs";
import { FormProvider, SchemaComponent } from "../../core/index.mjs";
import { useDesignable } from "../../hooks/index.mjs";
import { useProps } from "../../hooks/useProps.mjs";
import { Action } from "../action/index.mjs";
import { StablePopover } from "../popover/index.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: flex-end;\n      width: 100%;\n    "
    ]);
    _templateObject = function() {
        return data;
    };
    return data;
}
function _templateObject1() {
    const data = _tagged_template_literal([
        "\n      border-color: var(--colorSettings);\n      color: var(--colorSettings);\n    "
    ]);
    _templateObject1 = function() {
        return data;
    };
    return data;
}
const FilterActionContext = /*#__PURE__*/ createContext(null);
FilterActionContext.displayName = 'FilterActionContext';
const useStyles = createStyles((param)=>{
    let { css } = param;
    return {
        container: css(_templateObject()),
        button: css(_templateObject1())
    };
});
const FilterAction = withDynamicSchemaProps(observer((props)=>{
    const { styles } = useStyles();
    const { t } = useTranslation();
    const field = useField();
    const [visible, setVisible] = useState(false);
    const { designable, dn } = useDesignable();
    const fieldSchema = useFieldSchema();
    const form = useMemo(()=>props.form || createForm(), []);
    const { options, onSubmit, onReset, ...others } = useProps(props);
    const onOpenChange = useCallback((visible)=>{
        setVisible(visible);
    }, []);
    return /*#__PURE__*/ jsx(FilterActionContext.Provider, {
        value: {
            field,
            fieldSchema,
            designable,
            dn
        },
        children: /*#__PURE__*/ jsx(StablePopover, {
            destroyTooltipOnHide: true,
            placement: 'bottomLeft',
            open: visible,
            onOpenChange: onOpenChange,
            trigger: 'click',
            content: /*#__PURE__*/ jsx("form", {
                children: /*#__PURE__*/ jsxs(FormProvider, {
                    form: form,
                    children: [
                        /*#__PURE__*/ jsx(SchemaComponent, {
                            schema: {
                                type: 'object',
                                properties: {
                                    filter: {
                                        type: 'string',
                                        enum: options || field.dataSource,
                                        default: fieldSchema.default,
                                        'x-component': 'Filter',
                                        'x-component-props': {}
                                    }
                                }
                            }
                        }),
                        /*#__PURE__*/ jsx("div", {
                            className: styles.container,
                            children: /*#__PURE__*/ jsxs(Space, {
                                children: [
                                    /*#__PURE__*/ jsx(SaveConditions, {}),
                                    /*#__PURE__*/ jsx(Button, {
                                        onClick: async ()=>{
                                            await form.reset();
                                            null == onReset || onReset(form.values);
                                            field.title = t('Filter');
                                            setVisible(false);
                                        },
                                        children: t('Reset')
                                    }),
                                    /*#__PURE__*/ jsx(Button, {
                                        type: 'primary',
                                        htmlType: 'submit',
                                        onClick: (e)=>{
                                            e.preventDefault();
                                            e.stopPropagation();
                                            null == onSubmit || onSubmit(form.values);
                                            setVisible(false);
                                        },
                                        children: t('Submit')
                                    })
                                ]
                            })
                        })
                    ]
                })
            }),
            children: /*#__PURE__*/ jsx(Action, {
                ...others,
                title: field.title
            })
        })
    });
}), {
    displayName: 'FilterAction'
});
const SaveConditions = ()=>{
    const { fieldSchema, field, designable, dn } = useContext(FilterActionContext);
    const form = useForm();
    const { t } = useTranslation();
    const { styles } = useStyles();
    if (!designable) return null;
    return /*#__PURE__*/ jsx(Button, {
        type: 'dashed',
        className: styles.button,
        onClick: ()=>{
            const defaultValue = {
                ...form.values.filter
            };
            fieldSchema.default = defaultValue;
            dn.emit('patch', {
                schema: {
                    'x-uid': fieldSchema['x-uid'],
                    default: undefinedToNull(defaultValue)
                }
            });
            dn.refresh();
        },
        children: t('Save conditions')
    });
};
function undefinedToNull(value) {
    const flat = flatten(value);
    Object.keys(flat).forEach((key)=>{
        if (void 0 === flat[key]) flat[key] = null;
    });
    return unflatten(flat);
}
export { FilterAction, FilterActionContext };
