import { jsx, jsxs } from "react/jsx-runtime";
import { useMemo, useState } from "react";
import { FormLayout } from "@tachybase/components";
import { createForm, uid, useField, useForm } from "@tachybase/schema";
import { SyncOutlined } from "@ant-design/icons";
import { Button } from "antd";
import { useTranslation } from "react-i18next";
import { useAPIClient } from "../../api-client/index.mjs";
import { useCollectionParentRecordData } from "../../data-source/collection-record/CollectionRecordProvider.mjs";
import { RecordProvider, useRecord } from "../../record-provider/index.mjs";
import { ActionContextProvider, FormProvider, SchemaComponent, useActionContext } from "../../schema-component/index.mjs";
import { useCancelAction } from "../action-hooks.mjs";
import { useCollectionManager_deprecated } from "../hooks/useCollectionManager_deprecated.mjs";
import { useResourceActionContext, useResourceContext } from "../ResourceActionProvider.mjs";
import { FieldsConfigure, PreviewTable, SQLRequestProvider } from "../templates/components/sql-collection/index.mjs";
const schema = {
    type: 'object',
    properties: {
        [uid()]: {
            type: 'void',
            title: '{{ t("Sync from database") }}',
            'x-component': 'Action.Drawer',
            'x-decorator': 'FormLayout',
            'x-decorator-props': {
                layout: 'vertical'
            },
            properties: {
                config: {
                    type: 'void',
                    'x-decorator': SQLRequestProvider,
                    'x-decorator-props': {
                        manual: false
                    },
                    properties: {
                        sql: {
                            type: 'string'
                        },
                        sources: {
                            type: 'array',
                            title: '{{t("Source collections")}}',
                            'x-decorator': 'FormItem',
                            'x-component': 'Select',
                            'x-component-props': {
                                multiple: true
                            },
                            'x-reactions': [
                                '{{useAsyncDataSource(loadCollections)}}'
                            ]
                        },
                        fields: {
                            type: 'array',
                            title: '{{t("Fields")}}',
                            'x-decorator': 'FormItem',
                            'x-component': FieldsConfigure,
                            required: true
                        },
                        table: {
                            type: 'void',
                            title: '{{t("Preview")}}',
                            'x-decorator': 'FormItem',
                            'x-component': PreviewTable
                        }
                    }
                },
                footer: {
                    type: 'void',
                    'x-component': 'Action.Drawer.Footer',
                    properties: {
                        cancel: {
                            title: '{{ t("Cancel") }}',
                            'x-component': 'Action',
                            'x-component-props': {
                                useAction: '{{ useCancelAction }}'
                            }
                        },
                        submit: {
                            title: '{{ t("Submit") }}',
                            'x-component': 'Action',
                            'x-component-props': {
                                type: 'primary',
                                useAction: '{{ useSyncFromDB }}'
                            }
                        }
                    }
                }
            }
        }
    }
};
const useSyncFromDB = (refreshCMList)=>{
    const form = useForm();
    const ctx = useActionContext();
    const { refreshCM } = useCollectionManager_deprecated();
    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('sqlCollection').setFields({
                    filterByTk,
                    values: {
                        fields: form.values.fields,
                        sources: form.values.sources
                    }
                });
                ctx.setVisible(false);
                await form.reset();
                field.data.loading = false;
                refresh();
                await refreshCM();
                await (null == refreshCMList ? void 0 : refreshCMList());
            } catch (err) {
                field.data.loading = false;
            }
        }
    };
};
const SyncSQLFieldsAction = (param)=>{
    let { refreshCMList } = param;
    const record = useRecord();
    const parentRecordData = useCollectionParentRecordData();
    const { t } = useTranslation();
    const [visible, setVisible] = useState(false);
    const form = useMemo(()=>createForm({
            initialValues: record
        }), [
        record
    ]);
    return 'sql' === record.template && /*#__PURE__*/ jsx(RecordProvider, {
        record: record,
        parent: parentRecordData,
        children: /*#__PURE__*/ jsx(FormProvider, {
            form: form,
            children: /*#__PURE__*/ jsxs(ActionContextProvider, {
                value: {
                    visible,
                    setVisible
                },
                children: [
                    /*#__PURE__*/ jsx(Button, {
                        icon: /*#__PURE__*/ jsx(SyncOutlined, {}),
                        onClick: (e)=>setVisible(true),
                        children: t('Sync from database')
                    }),
                    /*#__PURE__*/ jsx(SchemaComponent, {
                        schema: schema,
                        components: {
                            FormLayout: FormLayout
                        },
                        scope: {
                            useCancelAction: useCancelAction,
                            useSyncFromDB: ()=>useSyncFromDB(refreshCMList)
                        }
                    })
                ]
            })
        })
    });
};
export { SyncSQLFieldsAction };
