import { jsx, jsxs } from "react/jsx-runtime";
import { useMemo, useRef, useState } from "react";
import { ArrayTable } from "@tachybase/components";
import { uid, useField, useForm } from "@tachybase/schema";
import { DownOutlined, PlusOutlined } from "@ant-design/icons";
import { Button, Dropdown } from "antd";
import { cloneDeep } from "lodash";
import { useTranslation } from "react-i18next";
import { useRequest } from "../../api-client/index.mjs";
import { RecordProvider, useRecord } from "../../record-provider/index.mjs";
import { ActionContextProvider, SchemaComponent, useActionContext, useCompile } from "../../schema-component/index.mjs";
import { useCancelAction } from "../action-hooks.mjs";
import { useCollectionManager_deprecated } from "../hooks/index.mjs";
import { useResourceActionContext, useResourceContext } from "../ResourceActionProvider.mjs";
import { TemplateSummary } from "./components/TemplateSummary.mjs";
import { ImportCollectionMetaAction } from "./ImportCollectionMetaAction.mjs";
import { ImportXlsxMetaAction } from "./ImportXlsx/ImportXlsxMetaAction.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__components_index_mjs_99c14d58__ from "./components/index.mjs";
const getSchema = (schema, category, compile)=>{
    if (!schema) return;
    const properties = cloneDeep(schema.configurableProperties);
    if (true === schema.hasDefaultValue) {
        properties['defaultValue'] = cloneDeep(schema.default.uiSchema);
        properties['defaultValue']['title'] = compile('{{ t("Default value") }}');
        properties['defaultValue']['x-decorator'] = 'FormItem';
    }
    const initialValue = {
        name: "t_".concat(uid()),
        template: schema.name,
        view: 'view' === schema.name,
        category,
        ...cloneDeep(schema.default)
    };
    if (initialValue.reverseField) initialValue.reverseField.name = "f_".concat(uid());
    return {
        type: 'object',
        properties: {
            [uid()]: {
                type: 'void',
                'x-component': 'Action.Drawer',
                'x-component-props': {
                    getContainer: '{{ getContainer }}'
                },
                'x-decorator': 'Form',
                'x-decorator-props': {
                    useValues (options) {
                        return useRequest(()=>Promise.resolve({
                                data: initialValue
                            }), options);
                    }
                },
                title: '{{ t("Create collection") }}',
                properties: {
                    summary: {
                        type: 'void',
                        'x-component': 'TemplateSummay',
                        'x-component-props': {
                            schemaKey: schema.name
                        }
                    },
                    ...properties,
                    footer: {
                        type: 'void',
                        'x-component': 'Action.Drawer.Footer',
                        properties: {
                            action1: {
                                title: '{{ t("Cancel") }}',
                                'x-component': 'Action',
                                'x-component-props': {
                                    useAction: '{{ useCancelAction }}'
                                }
                            },
                            action2: {
                                title: '{{ t("Submit") }}',
                                'x-component': 'Action',
                                'x-component-props': {
                                    type: 'primary',
                                    useAction: ()=>useCreateCollection(schema)
                                }
                            }
                        }
                    }
                }
            }
        }
    };
};
const useCreateCollection = (schema)=>{
    const form = useForm();
    const { refreshCM } = useCollectionManager_deprecated();
    const ctx = useActionContext();
    const { refresh } = useResourceActionContext();
    const { resource } = useResourceContext();
    const field = useField();
    return {
        async run () {
            field.data = field.data || {};
            field.data.loading = true;
            try {
                var _schema_events;
                await form.submit();
                const values = cloneDeep(form.values);
                if (null == schema ? void 0 : null == (_schema_events = schema.events) ? void 0 : _schema_events.beforeSubmit) schema.events.beforeSubmit(values);
                if (!values.autoCreateReverseField) delete values.reverseField;
                delete values.autoCreateReverseField;
                await resource.create({
                    values: {
                        logging: true,
                        ...values
                    }
                });
                ctx.setVisible(false);
                await form.reset();
                field.data.loading = false;
                refresh();
                await refreshCM();
            } catch (error) {
                field.data.loading = false;
            }
        }
    };
};
const AddCollection = (props)=>{
    const recordData = useRecord();
    return /*#__PURE__*/ jsx(AddCollectionAction, {
        item: recordData,
        ...props
    });
};
const AddCollectionAction = (props)=>{
    const { scope, getContainer, item: record, children, trigger, align } = props;
    const { getTemplate, templates: collectionTemplates } = useCollectionManager_deprecated();
    const [visible, setVisible] = useState(false);
    const [schema, setSchema] = useState({});
    const compile = useCompile();
    const { t } = useTranslation();
    const importRef = useRef(null);
    const importxlsxRef = useRef(null);
    const items = useMemo(()=>{
        const result = [];
        collectionTemplates.forEach((item)=>{
            if (item.divider) result.push({
                type: 'divider'
            });
            result.push({
                label: compile(item.title),
                key: item.name
            });
        });
        return result;
    }, [
        collectionTemplates
    ]);
    const { state: { category } } = useResourceActionContext();
    const menu = useMemo(()=>({
            style: {
                maxHeight: '60vh',
                overflow: 'auto'
            },
            onClick: (info)=>{
                if ('import' === info.key) {
                    var _importRef_current;
                    null == (_importRef_current = importRef.current) || _importRef_current.showModal();
                    return;
                }
                if ('importXlsx' === info.key) {
                    var _importxlsxRef_current;
                    null == (_importxlsxRef_current = importxlsxRef.current) || _importxlsxRef_current.showModal();
                    return;
                }
                const schema = getSchema(getTemplate(info.key), category, compile);
                setSchema(schema);
                setVisible(true);
            },
            items
        }), [
        category,
        items,
        importRef,
        importxlsxRef
    ]);
    return /*#__PURE__*/ jsxs(RecordProvider, {
        record: record,
        children: [
            /*#__PURE__*/ jsxs(ActionContextProvider, {
                value: {
                    visible,
                    setVisible
                },
                children: [
                    /*#__PURE__*/ jsx(Dropdown, {
                        getPopupContainer: getContainer,
                        trigger: trigger,
                        align: align,
                        menu: menu,
                        children: children || /*#__PURE__*/ jsxs(Button, {
                            icon: /*#__PURE__*/ jsx(PlusOutlined, {}),
                            type: 'primary',
                            children: [
                                t('Create collection'),
                                " ",
                                /*#__PURE__*/ jsx(DownOutlined, {})
                            ]
                        })
                    }),
                    /*#__PURE__*/ jsx(SchemaComponent, {
                        schema: schema,
                        components: {
                            ...__WEBPACK_EXTERNAL_MODULE__components_index_mjs_99c14d58__,
                            ArrayTable: ArrayTable,
                            TemplateSummay: TemplateSummary
                        },
                        scope: {
                            getContainer,
                            useCancelAction: useCancelAction,
                            createOnly: true,
                            useCreateCollection,
                            record,
                            showReverseFieldConfig: true,
                            ...scope
                        }
                    })
                ]
            }),
            /*#__PURE__*/ jsx(ImportCollectionMetaAction, {
                ref: importRef
            }),
            /*#__PURE__*/ jsx(ImportXlsxMetaAction, {
                ref: importxlsxRef
            })
        ]
    });
};
export { AddCollection, AddCollectionAction };
