import { jsx, jsxs } from "react/jsx-runtime";
import { useEffect, useState } from "react";
import { uid, useForm } from "@tachybase/schema";
import { ArrayTable } from "@tego/client";
import cloneDeep from "lodash/cloneDeep";
import omit from "lodash/omit";
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 * as __WEBPACK_EXTERNAL_MODULE__components_index_mjs_99c14d58__ from "./components/index.mjs";
const getSchema = (schema, record, compile, getContainer)=>{
    if (!schema) return;
    const properties = cloneDeep(schema.configurableProperties) || {
        title: {
            'x-component': 'CollectionField',
            'x-decorator': 'FormItem'
        },
        name: {
            'x-component': 'CollectionField',
            'x-decorator': 'FormItem'
        }
    };
    if (true === schema.hasDefaultValue) {
        properties['defaultValue'] = cloneDeep(schema.default.uiSchema);
        properties['defaultValue']['title'] = compile('{{ t("Default value") }}');
        properties['defaultValue']['x-decorator'] = 'FormItem';
    }
    return {
        type: 'object',
        properties: {
            [uid()]: {
                type: 'void',
                'x-component': 'Action.Drawer',
                'x-decorator': 'Form',
                'x-decorator-props': {
                    useValues: '{{ useValuesFromRecord }}'
                },
                title: '{{ t("Edit collection") }}',
                properties: {
                    ...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: '{{ useUpdateCollectionActionAndRefreshCM }}'
                                }
                            }
                        }
                    }
                }
            }
        }
    };
};
const useValuesFromRecord = (options)=>{
    const record = useRecord();
    const result = useRequest(()=>Promise.resolve({
            data: {
                ...omit(cloneDeep(record), [
                    '__parent',
                    '__collectionName'
                ]),
                category: null == record ? void 0 : record.category.map((v)=>v.id)
            }
        }), {
        ...options,
        manual: true
    });
    const ctx = useActionContext();
    useEffect(()=>{
        if (ctx.visible) result.run();
    }, [
        ctx.visible
    ]);
    return result;
};
const useUpdateCollectionActionAndRefreshCM = (options)=>{
    const { refreshCM } = useCollectionManager_deprecated();
    const form = useForm();
    const ctx = useActionContext();
    const { refresh } = useResourceActionContext();
    const { resource, targetKey } = useResourceContext();
    const { [targetKey]: filterByTk, template } = useRecord();
    const api = useAPIClient();
    const collectionResource = 'sql' === template ? api.resource('sqlCollection') : resource;
    return {
        async run () {
            await form.submit();
            await collectionResource.update({
                filterByTk,
                values: 'sql' === template ? form.values : omit(form.values, [
                    'fields'
                ])
            });
            ctx.setVisible(false);
            await form.reset();
            refresh();
            await refreshCM();
        }
    };
};
const EditCollection = (props)=>{
    const record = useRecord();
    return /*#__PURE__*/ jsx(EditCollectionAction, {
        item: record,
        ...props
    });
};
const EditCollectionAction = (props)=>{
    const { scope, getContainer, item: record, children, ...otherProps } = props;
    const { getTemplate } = useCollectionManager_deprecated();
    const [visible, setVisible] = useState(false);
    const [schema, setSchema] = useState({});
    const { t } = useTranslation();
    const compile = useCompile();
    return /*#__PURE__*/ jsx(RecordProvider, {
        record: record,
        children: /*#__PURE__*/ jsxs(ActionContextProvider, {
            value: {
                visible,
                setVisible
            },
            children: [
                /*#__PURE__*/ jsx("a", {
                    ...otherProps,
                    onClick: async ()=>{
                        const templateConf = getTemplate(record.template);
                        const schema = getSchema({
                            ...templateConf
                        }, record, compile, getContainer);
                        setSchema(schema);
                        setVisible(true);
                    },
                    children: children || t('Edit')
                }),
                /*#__PURE__*/ jsx(SchemaComponent, {
                    schema: schema,
                    components: {
                        ...__WEBPACK_EXTERNAL_MODULE__components_index_mjs_99c14d58__,
                        ArrayTable: ArrayTable
                    },
                    scope: {
                        getContainer,
                        useValuesFromRecord,
                        useUpdateCollectionActionAndRefreshCM,
                        useCancelAction: useCancelAction,
                        createOnly: false,
                        ...scope
                    }
                })
            ]
        })
    });
};
export { EditCollection, EditCollectionAction, useUpdateCollectionActionAndRefreshCM, useValuesFromRecord };
