import { jsx, jsxs } from "react/jsx-runtime";
import { useState } from "react";
import { ArrayTable } from "@tachybase/components";
import { uid, useField, useForm } from "@tachybase/schema";
import { PlusOutlined } from "@ant-design/icons";
import { Button } from "antd";
import { cloneDeep } from "lodash";
import { useTranslation } from "react-i18next";
import { useAPIClient, 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 { PreviewFields } from "../templates/components/PreviewFields.mjs";
import { PreviewTable } from "../templates/components/PreviewTable.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__components_index_mjs_99c14d58__ from "./components/index.mjs";
const getSchema = (schema, record, compile)=>{
    if (!schema) return;
    const properties = cloneDeep(schema.properties);
    if (true === schema.hasDefaultValue) {
        var _schema_default;
        properties['defaultValue'] = cloneDeep(null == schema ? void 0 : null == (_schema_default = schema.default) ? void 0 : _schema_default.uiSchema);
        properties['defaultValue']['title'] = compile('{{ t("Default value") }}');
        properties['defaultValue']['x-decorator'] = 'FormItem';
    }
    const initialValue = {
        name: "f_".concat(uid()),
        ...cloneDeep(schema.default),
        interface: schema.name
    };
    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: "".concat(compile('{{ t("Sync from database") }}')),
                properties: {
                    schema: {
                        type: 'string',
                        'x-hidden': true,
                        default: null == record ? void 0 : record.schema
                    },
                    viewName: {
                        type: 'string',
                        'x-hidden': true,
                        default: null == record ? void 0 : record.viewName
                    },
                    fields: {
                        type: 'array',
                        'x-component': PreviewFields,
                        'x-component-props': {
                            ...record
                        },
                        default: record.fields
                    },
                    preview: {
                        type: 'object',
                        'x-component': PreviewTable,
                        'x-component-props': {
                            ...record
                        },
                        'x-reactions': {
                            dependencies: [
                                'fields'
                            ],
                            fulfill: {
                                schema: {
                                    'x-component-props': '{{{...record,...$form.values}}}'
                                }
                            }
                        }
                    },
                    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: '{{ useSyncFromDatabase }}'
                                }
                            }
                        }
                    }
                }
            }
        }
    };
};
const useSyncFromDatabase = ()=>{
    const form = useForm();
    const { refreshCM } = useCollectionManager_deprecated();
    const ctx = useActionContext();
    const { refresh } = useResourceActionContext();
    const { targetKey } = useResourceContext();
    const { [targetKey]: filterByTk } = useRecord();
    const api = useAPIClient();
    const field = useField();
    return {
        async run () {
            await form.submit();
            field.data = field.data || {};
            field.data.loading = true;
            try {
                await api.resource("collections").setFields({
                    filterByTk,
                    values: form.values
                });
                ctx.setVisible(false);
                await form.reset();
                field.data.loading = false;
                refresh();
                await refreshCM();
            } catch (error) {
                field.data.loading = false;
            }
        }
    };
};
const SyncFieldsAction = (props)=>{
    const record = useRecord();
    return /*#__PURE__*/ jsx(SyncFieldsActionCom, {
        item: record,
        ...props
    });
};
const SyncFieldsActionCom = (props)=>{
    const { scope, getContainer, item: record, children } = props;
    const [visible, setVisible] = useState(false);
    const [schema, setSchema] = useState({});
    const compile = useCompile();
    const { t } = useTranslation();
    return 'view' === record.template && /*#__PURE__*/ jsx(RecordProvider, {
        record: record,
        children: /*#__PURE__*/ jsxs(ActionContextProvider, {
            value: {
                visible,
                setVisible,
                drawerProps: {
                    width: 900
                }
            },
            children: [
                children || /*#__PURE__*/ jsx(Button, {
                    icon: /*#__PURE__*/ jsx(PlusOutlined, {}),
                    onClick: (e)=>{
                        const schema = getSchema({}, record, compile);
                        if (schema) {
                            setSchema(schema);
                            setVisible(true);
                        }
                    },
                    children: t('Sync from database')
                }),
                /*#__PURE__*/ jsx(SchemaComponent, {
                    schema: schema,
                    components: {
                        ...__WEBPACK_EXTERNAL_MODULE__components_index_mjs_99c14d58__,
                        ArrayTable: ArrayTable
                    },
                    scope: {
                        getContainer,
                        useCancelAction: useCancelAction,
                        createOnly: true,
                        isOverride: false,
                        useSyncFromDatabase,
                        record,
                        ...scope
                    }
                })
            ]
        })
    });
};
export { SyncFieldsAction, SyncFieldsActionCom };
