import { useState } from "react";
import { useField, useFieldSchema } from "@tachybase/schema";
import { ArrayItems, Switch } from "@tego/client";
import { useTranslation } from "react-i18next";
import { SchemaSettings } from "../../../../application/schema-settings/SchemaSettings.mjs";
import { useCollectionManager_deprecated, useSortFields } from "../../../../collection-manager/index.mjs";
import { useFieldComponentName } from "../../../../common/useFieldComponentName.mjs";
import { useCollectionManager } from "../../../../data-source/index.mjs";
import { useCompile, useDesignable, useFieldModeOptions, useIsAddNewForm } from "../../../../schema-component/index.mjs";
import { isSubMode } from "../../../../schema-component/antd/association-field/util.mjs";
import { useIsAssociationField, useIsFieldReadPretty } from "../../../../schema-component/antd/form-item/index.mjs";
import { SecondLevelSelect } from "./secondLevelSelect.mjs";
const fieldComponent = {
    name: 'fieldComponent',
    type: 'select',
    useComponentProps () {
        const { t } = useTranslation();
        const field = useField();
        const fieldSchema = useFieldSchema();
        const fieldModeOptions = useFieldModeOptions();
        const isAddNewForm = useIsAddNewForm();
        const fieldComponentName = useFieldComponentName();
        const { dn } = useDesignable();
        return {
            title: t('Field component'),
            options: fieldModeOptions,
            value: fieldComponentName,
            onChange (mode) {
                const schema = {
                    ['x-uid']: fieldSchema['x-uid']
                };
                fieldSchema['x-component-props'] = fieldSchema['x-component-props'] || {};
                fieldSchema['x-component-props']['mode'] = mode;
                schema['x-component-props'] = fieldSchema['x-component-props'];
                field.componentProps = field.componentProps || {};
                field.componentProps.mode = mode;
                if (isSubMode(fieldSchema) && isAddNewForm) {
                    schema.default = null;
                    fieldSchema.default = null;
                    field.setInitialValue(null);
                    field.setValue(null);
                }
                dn.emit('patch', {
                    schema
                });
                dn.refresh();
            }
        };
    }
};
const allowSelectExistingRecord = {
    name: 'allowSelectExistingRecord',
    type: 'switch',
    useVisible () {
        const readPretty = useIsFieldReadPretty();
        return !readPretty;
    },
    useComponentProps () {
        var _fieldSchema_xcomponentprops;
        const { t } = useTranslation();
        const field = useField();
        const fieldSchema = useFieldSchema();
        const { dn, refresh } = useDesignable();
        return {
            title: t('Allow selection of existing records'),
            checked: null == (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops.allowSelectExistingRecord,
            onChange (value) {
                const schema = {
                    ['x-uid']: fieldSchema['x-uid']
                };
                field.componentProps.allowSelectExistingRecord = value;
                fieldSchema['x-component-props'] = fieldSchema['x-component-props'] || {};
                fieldSchema['x-component-props'].allowSelectExistingRecord = value;
                schema['x-component-props'] = fieldSchema['x-component-props'];
                dn.emit('patch', {
                    schema
                });
                refresh();
            }
        };
    }
};
const setDefaultSortingRules = {
    name: 'SetDefaultSortingRules',
    type: 'modal',
    useComponentProps () {
        const { getCollectionJoinField } = useCollectionManager_deprecated();
        const field = useField();
        const fieldSchema = useFieldSchema();
        const association = fieldSchema['x-collection-field'];
        const { target } = getCollectionJoinField(association) || {};
        const sortFields = useSortFields(target);
        const { t } = useTranslation();
        const { dn } = useDesignable();
        const defaultSort = field.componentProps.sortArr || [];
        const sort = null == defaultSort ? void 0 : defaultSort.map((item)=>(null == item ? void 0 : item.startsWith('-')) ? {
                field: item.substring(1),
                direction: 'desc'
            } : {
                field: item,
                direction: 'asc'
            });
        return {
            title: t('Set default sorting rules'),
            components: {
                ArrayItems: ArrayItems
            },
            schema: {
                type: 'object',
                title: t('Set default sorting rules'),
                properties: {
                    sort: {
                        type: 'array',
                        default: sort,
                        'x-component': 'ArrayItems',
                        'x-decorator': 'FormItem',
                        items: {
                            type: 'object',
                            properties: {
                                space: {
                                    type: 'void',
                                    'x-component': 'Space',
                                    properties: {
                                        sort: {
                                            type: 'void',
                                            'x-decorator': 'FormItem',
                                            'x-component': 'ArrayItems.SortHandle'
                                        },
                                        field: {
                                            type: 'string',
                                            enum: sortFields,
                                            required: true,
                                            'x-decorator': 'FormItem',
                                            'x-component': 'Select',
                                            'x-component-props': {
                                                style: {
                                                    width: 260
                                                },
                                                optionLabelProp: 'fullLabel'
                                            }
                                        },
                                        direction: {
                                            type: 'string',
                                            'x-decorator': 'FormItem',
                                            'x-component': 'Radio.Group',
                                            'x-component-props': {
                                                optionType: 'button'
                                            },
                                            enum: [
                                                {
                                                    label: t('ASC'),
                                                    value: 'asc'
                                                },
                                                {
                                                    label: t('DESC'),
                                                    value: 'desc'
                                                }
                                            ]
                                        },
                                        remove: {
                                            type: 'void',
                                            'x-decorator': 'FormItem',
                                            'x-component': 'ArrayItems.Remove'
                                        }
                                    }
                                }
                            }
                        },
                        properties: {
                            add: {
                                type: 'void',
                                title: t('Add sort field'),
                                'x-component': 'ArrayItems.Addition'
                            }
                        }
                    }
                }
            },
            onSubmit: (param)=>{
                let { sort } = param;
                const sortArr = sort.map((item)=>'desc' === item.direction ? "-".concat(item.field) : item.field);
                field.componentProps.sortArr = sortArr;
                fieldSchema['x-component-props'].sortArr = sortArr;
                dn.emit('patch', {
                    schema: {
                        ['x-uid']: fieldSchema['x-uid'],
                        'x-component-props': fieldSchema['x-component-props']
                    }
                });
            }
        };
    },
    useVisible () {
        const { getCollectionJoinField } = useCollectionManager_deprecated();
        const fieldSchema = useFieldSchema();
        const association = fieldSchema['x-collection-field'];
        const { interface: targetInterface } = getCollectionJoinField(association) || {};
        const readPretty = useIsFieldReadPretty();
        return readPretty && [
            'm2m',
            'o2m'
        ].includes(targetInterface);
    }
};
const allowAddNewData = {
    name: 'allowAddNewData',
    type: 'switch',
    useVisible () {
        const readPretty = useIsFieldReadPretty();
        const isAssociationField = useIsAssociationField();
        return !readPretty && isAssociationField;
    },
    useComponentProps () {
        var _fieldSchema_xcomponentprops;
        const { t } = useTranslation();
        const field = useField();
        const fieldSchema = useFieldSchema();
        const { dn, refresh } = useDesignable();
        return {
            title: t('Allow add new'),
            checked: (null == (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops.allowAddnew) !== false,
            onChange (value) {
                const schema = {
                    ['x-uid']: fieldSchema['x-uid']
                };
                field.componentProps.allowAddnew = value;
                fieldSchema['x-component-props'] = fieldSchema['x-component-props'] || {};
                fieldSchema['x-component-props'].allowAddnew = value;
                schema['x-component-props'] = fieldSchema['x-component-props'];
                dn.emit('patch', {
                    schema
                });
                refresh();
            }
        };
    }
};
const clickToSelect = {
    name: 'clicktoselect',
    type: 'modal',
    useVisible () {
        const readPretty = useIsFieldReadPretty();
        const isAssociationField = useIsAssociationField();
        return !readPretty && isAssociationField;
    },
    useComponentProps () {
        var _fieldSchema_xcomponentprops_quickAddField, _fieldSchema_xcomponentprops_quickAddParentCollection, _fieldSchema_xcomponentprops, _fieldSchema_xcomponentprops1;
        const { t } = useTranslation();
        const field = useField();
        const fieldSchema = useFieldSchema();
        const { dn, refresh } = useDesignable();
        const compile = useCompile();
        const cm = useCollectionManager();
        const [firstLevelValue, setFirstLevelValue] = useState((null == (_fieldSchema_xcomponentprops_quickAddField = fieldSchema['x-component-props']['quickAddField']) ? void 0 : _fieldSchema_xcomponentprops_quickAddField.value) || 'none');
        const options = cm.getCollection(fieldSchema['x-collection-field']);
        const isAddNewForm = useIsAddNewForm();
        const fieldTabsOptions = options.fields.map((item)=>{
            if ('m2o' === item.interface || 'select' === item.interface) {
                var _item_uiSchema;
                return {
                    ...item,
                    label: compile(null == (_item_uiSchema = item.uiSchema) ? void 0 : _item_uiSchema.title),
                    value: item.name
                };
            }
        }).filter(Boolean);
        fieldTabsOptions.unshift({
            label: 'none',
            value: 'none'
        });
        const Parentoptions = cm.getCollectionFields("".concat(fieldSchema['x-collection-field'], ".").concat(firstLevelValue));
        const fieldParentTabsOptions = Parentoptions.map((item)=>{
            if ('m2o' === item.interface) return {
                ...item,
                label: compile(item.uiSchema.title),
                value: item.name
            };
        }).filter(Boolean);
        fieldParentTabsOptions.unshift({
            label: t('none'),
            value: 'none'
        });
        const defParentVal = (null == (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) ? void 0 : null == (_fieldSchema_xcomponentprops_quickAddParentCollection = _fieldSchema_xcomponentprops['quickAddParentCollection']) ? void 0 : _fieldSchema_xcomponentprops_quickAddParentCollection.value) || 'none';
        const schema = {
            type: 'object',
            title: t('Click to select'),
            properties: {
                isquickaddtabs: {
                    title: t('Enable quick create'),
                    type: 'boolean',
                    default: (null == (_fieldSchema_xcomponentprops1 = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops1.isQuickAdd) || false,
                    'x-decorator': 'FormItem',
                    'x-component': 'Switch',
                    'x-component-props': {}
                },
                firstLevelselection: {
                    title: t('Set Quick Add Tabs'),
                    default: firstLevelValue,
                    'x-decorator': 'FormItem',
                    'x-component': 'Select',
                    enum: fieldTabsOptions,
                    'x-reactions': [
                        {
                            dependencies: [
                                'isquickaddtabs'
                            ],
                            fulfill: {
                                state: {
                                    visible: '{{$deps[0] === true}}'
                                }
                            }
                        }
                    ],
                    'x-component-props': {
                        onChange (value) {
                            setFirstLevelValue(value);
                        }
                    }
                },
                secondLevelselection: {
                    title: t('Set Quick Add Parent Tabs'),
                    default: defParentVal,
                    'x-decorator': 'FormItem',
                    'x-component': 'SecondLevelSelect',
                    'x-reactions': [
                        {
                            dependencies: [
                                'firstLevelselection',
                                'isquickaddtabs'
                            ],
                            fulfill: {
                                state: {
                                    visible: '{{$deps[0] !== "none" && $deps[1] === true}}'
                                },
                                schema: {
                                    'x-component-props': {
                                        firstLevelValue: '{{$deps[0]}}',
                                        collectionField: fieldSchema['x-collection-field']
                                    }
                                }
                            }
                        }
                    ]
                }
            }
        };
        return {
            components: {
                Switch: Switch,
                SecondLevelSelect: SecondLevelSelect
            },
            title: t('Quick create'),
            schema,
            onSubmit: async (param)=>{
                let { isquickaddtabs, firstLevelselection, secondLevelselection } = param;
                var _fieldTabsOptions_find;
                const schema = {
                    ['x-uid']: fieldSchema['x-uid']
                };
                field.componentProps['isQuickAdd'] = isquickaddtabs;
                fieldSchema['x-component-props'] = fieldSchema['x-component-props'] || {};
                fieldSchema['x-component-props']['isQuickAdd'] = isquickaddtabs;
                schema['x-component-props'] = fieldSchema['x-component-props'];
                fieldSchema['x-component-props'] = fieldSchema['x-component-props'] || {};
                fieldSchema['x-component-props']['quickAddField'] = {
                    fieldInterface: (null == (_fieldTabsOptions_find = fieldTabsOptions.find((item)=>item.value === firstLevelselection)) ? void 0 : _fieldTabsOptions_find['interface']) || 'none',
                    value: firstLevelselection
                };
                schema['x-component-props'] = fieldSchema['x-component-props'];
                field.componentProps = field.componentProps || {};
                field.componentProps['quickAddField'] = fieldSchema['x-component-props']['quickAddField'];
                fieldSchema['x-component-props'] = fieldSchema['x-component-props'] || {};
                fieldSchema['x-component-props']['quickAddParentCollection'] = {
                    collectionField: "".concat(fieldSchema['x-collection-field'], ".").concat(firstLevelselection, ".").concat(secondLevelselection),
                    value: secondLevelselection
                };
                schema['x-component-props'] = fieldSchema['x-component-props'];
                field.componentProps = field.componentProps || {};
                field.componentProps['quickAddParentCollection'] = {
                    collectionField: "".concat(fieldSchema['x-collection-field'], ".").concat(firstLevelselection, ".").concat(secondLevelselection),
                    value: secondLevelselection
                };
                if (isSubMode(fieldSchema) && isAddNewForm) {
                    schema.default = null;
                    fieldSchema.default = null;
                    field.setInitialValue(null);
                    field.setValue(null);
                }
                dn.emit('patch', {
                    schema: schema
                });
                refresh();
                dn.refresh();
            }
        };
    }
};
const tablePagination = {
    name: 'tablePagination',
    type: 'switch',
    useComponentProps () {
        var _fieldSchema_xcomponentprops;
        const { dn } = useDesignable();
        const fieldSchema = useFieldSchema();
        const { t } = useTranslation();
        const field = useField();
        return {
            title: t('Pagination'),
            checked: (null == (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops.pagination) || false,
            onChange (v) {
                if (!fieldSchema['x-component-props'].pagination) fieldSchema['x-component-props'] = {
                    ...fieldSchema['x-component-props'],
                    pagination: false
                };
                fieldSchema['x-component-props'].pagination = v;
                field.componentProps['pagination'] = v;
                dn.emit('patch', {
                    schema: {
                        'x-uid': fieldSchema['x-uid'],
                        'x-component-props': {
                            ...null == fieldSchema ? void 0 : fieldSchema['x-component-props']
                        }
                    }
                });
                dn.refresh();
            }
        };
    }
};
const subTablePopoverComponentFieldSettings = new SchemaSettings({
    name: 'fieldSettings:component:SubTable',
    items: [
        fieldComponent,
        allowAddNewData,
        allowSelectExistingRecord,
        setDefaultSortingRules,
        clickToSelect,
        tablePagination
    ]
});
export { allowAddNewData, clickToSelect, setDefaultSortingRules, subTablePopoverComponentFieldSettings, tablePagination };
