import { jsx, jsxs } from "react/jsx-runtime";
import { useMemo, 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 set from "lodash/set";
import { useTranslation } from "react-i18next";
import { useAPIClient, useRequest } from "../../api-client/index.mjs";
import { useCollectionParentRecordData } from "../../data-source/collection-record/CollectionRecordProvider.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 useDialect from "../hooks/useDialect.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)=>{
    var _record___parent;
    if (!schema) return;
    const properties = cloneDeep(schema.properties);
    if (null == properties ? void 0 : properties.name) properties.name['x-disabled'] = true;
    if (true === schema.hasDefaultValue) {
        properties['defaultValue'] = cloneDeep(schema.default.uiSchema) || {};
        properties.defaultValue.required = false;
        properties['defaultValue']['title'] = compile('{{ t("Default value") }}');
        properties['defaultValue']['x-decorator'] = 'FormItem';
        properties['defaultValue']['x-reactions'] = [
            {
                dependencies: [
                    'uiSchema.x-component-props.gmt',
                    'uiSchema.x-component-props.showTime',
                    'uiSchema.x-component-props.dateFormat',
                    'uiSchema.x-component-props.timeFormat'
                ],
                fulfill: {
                    state: {
                        componentProps: {
                            gmt: '{{$deps[0]}}',
                            showTime: '{{$deps[1]}}',
                            dateFormat: '{{$deps[2]}}',
                            timeFormat: '{{$deps[3]}}'
                        }
                    }
                }
            },
            {
                dependencies: [
                    'primaryKey',
                    'unique',
                    'autoIncrement'
                ],
                when: '{{$deps[0]||$deps[1]||$deps[2]}}',
                fulfill: {
                    state: {
                        hidden: true,
                        value: void 0
                    }
                },
                otherwise: {
                    state: {
                        hidden: false
                    }
                }
            }
        ];
    }
    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: cloneDeep(omit(schema.default, [
                                    'uiSchema.rawTitle'
                                ]))
                            }), options);
                    }
                },
                title: "".concat(compile(null == (_record___parent = record.__parent) ? void 0 : _record___parent.title), " - ").concat(compile('{{ t("Edit field") }}')),
                properties: {
                    summary: {
                        type: 'void',
                        'x-component': 'FieldSummary',
                        'x-component-props': {
                            schemaKey: schema.name
                        }
                    },
                    ...properties,
                    description: {
                        type: 'string',
                        title: '{{t("Description")}}',
                        'x-decorator': 'FormItem',
                        'x-component': 'Input.TextArea'
                    },
                    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: '{{ useUpdateCollectionField }}'
                                }
                            }
                        }
                    }
                }
            }
        }
    };
};
const useUpdateCollectionField = ()=>{
    const form = useForm();
    const { refreshCM } = useCollectionManager_deprecated();
    const ctx = useActionContext();
    const { refresh } = useResourceActionContext();
    const { resource, targetKey } = useResourceContext();
    const { [targetKey]: filterByTk } = useRecord();
    return {
        async run () {
            await form.submit();
            const values = cloneDeep(form.values);
            values.autoCreateReverseField || delete values.reverseField;
            delete values.autoCreateReverseField;
            await resource.update({
                filterByTk,
                values
            });
            ctx.setVisible(false);
            await form.reset();
            refresh();
            await refreshCM();
        }
    };
};
const EditCollectionField = (props)=>{
    const record = useRecord();
    const parentRecordData = useCollectionParentRecordData();
    return /*#__PURE__*/ jsx(EditFieldAction, {
        item: record,
        parentItem: parentRecordData,
        ...props
    });
};
const EditFieldAction = (props)=>{
    const { scope, getContainer, item: record, parentItem: parentRecord, children, ...otherProps } = props;
    const { getInterface, collections, getCollection } = useCollectionManager_deprecated();
    const [visible, setVisible] = useState(false);
    const [schema, setSchema] = useState({});
    const api = useAPIClient();
    const { t } = useTranslation();
    const compile = useCompile();
    const [data, setData] = useState({});
    const { isDialect } = useDialect();
    const scopeKeyOptions = useMemo(()=>(null == record ? void 0 : record.fields) || getCollection(record.collectionName).options.fields.filter((v)=>'select' === v.interface).map((k)=>{
            var _k_uiSchema;
            return {
                value: k.name,
                label: compile(null == (_k_uiSchema = k.uiSchema) ? void 0 : _k_uiSchema.title)
            };
        }), [
        record.name
    ]);
    const currentCollections = useMemo(()=>collections.map((v)=>({
                label: compile(v.title),
                value: v.name
            })), []);
    return /*#__PURE__*/ jsx(RecordProvider, {
        record: record,
        parent: parentRecord,
        children: /*#__PURE__*/ jsxs(ActionContextProvider, {
            value: {
                visible,
                setVisible
            },
            children: [
                /*#__PURE__*/ jsx("a", {
                    ...otherProps,
                    onClick: async ()=>{
                        const { data } = await api.resource('collections.fields', record.collectionName).get({
                            filterByTk: record.name,
                            appends: [
                                'reverseField'
                            ]
                        });
                        setData(null == data ? void 0 : data.data);
                        const interfaceConf = getInterface(record.interface);
                        const defaultValues = cloneDeep(null == data ? void 0 : data.data) || {};
                        if (!(null == defaultValues ? void 0 : defaultValues.reverseField)) {
                            var _interfaceConf_default, _record___parent;
                            defaultValues.autoCreateReverseField = false;
                            defaultValues.reverseField = null == interfaceConf ? void 0 : null == (_interfaceConf_default = interfaceConf.default) ? void 0 : _interfaceConf_default.reverseField;
                            set(defaultValues.reverseField, 'name', "f_".concat(uid()));
                            set(defaultValues.reverseField, 'uiSchema.title', null == (_record___parent = record.__parent) ? void 0 : _record___parent.title);
                        }
                        const schema = getSchema({
                            ...interfaceConf,
                            default: defaultValues
                        }, 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,
                        useUpdateCollectionField,
                        useCancelAction: useCancelAction,
                        showReverseFieldConfig: !(null == data ? void 0 : data.reverseField),
                        collections: currentCollections,
                        isDialect,
                        disabledJSONB: true,
                        scopeKeyOptions,
                        createMainOnly: true,
                        ...scope
                    }
                })
            ]
        })
    });
};
export { EditCollectionField, EditFieldAction };
