import { jsx, jsxs } from "react/jsx-runtime";
import { useContext } from "react";
import { ArrayItems } from "@tachybase/components";
import { useField, useFieldSchema } from "@tachybase/schema";
import lodash from "lodash";
import { useTranslation } from "react-i18next";
import { useFormBlockContext, useTableSelectorContext } from "../../../block-provider/index.mjs";
import { recursiveParent } from "../../../block-provider/TableSelectorProvider.mjs";
import { useCollectionManager_deprecated, useCollection_deprecated } from "../../../collection-manager/index.mjs";
import { useSortFields } from "../../../collection-manager/action-hooks.mjs";
import { SetDataLoadingMode } from "../../../modules/blocks/data-blocks/details-multi/setDataLoadingModeSettingsItem.mjs";
import { useRecord } from "../../../record-provider/index.mjs";
import { GeneralSchemaDesigner, SchemaSettingsDivider, SchemaSettingsModalItem, SchemaSettingsRemove, SchemaSettingsSelectItem, SchemaSettingsSwitchItem } from "../../../schema-settings/index.mjs";
import { SchemaSettingsDataScope } from "../../../schema-settings/SchemaSettingsDataScope.mjs";
import { VariableInput, getShouldChange } from "../../../schema-settings/VariableInput/VariableInput.mjs";
import { useSchemaTemplate } from "../../../schema-templates/index.mjs";
import { useLocalVariables, useVariables } from "../../../variables/index.mjs";
import { RecordPickerContext } from "../record-picker/index.mjs";
import { useDesignable } from "../../hooks/index.mjs";
import { removeNullCondition } from "../filter/index.mjs";
const TableSelectorDesigner = ()=>{
    var _fieldSchema_xdecoratorprops_params, _fieldSchema_xdecoratorprops, _fieldSchema_xdecoratorprops_params1, _fieldSchema_xdecoratorprops1, _field_decoratorProps_params, _field_decoratorProps;
    const { name, title } = useCollection_deprecated();
    const { getCollectionJoinField, getAllCollectionsInheritChain } = useCollectionManager_deprecated();
    const field = useField();
    const fieldSchema = useFieldSchema();
    const { form } = useFormBlockContext();
    const sortFields = useSortFields(name);
    const { service, extraFilter } = useTableSelectorContext();
    const { t } = useTranslation();
    const { dn } = useDesignable();
    const defaultSort = (null == fieldSchema ? void 0 : null == (_fieldSchema_xdecoratorprops = fieldSchema['x-decorator-props']) ? void 0 : null == (_fieldSchema_xdecoratorprops_params = _fieldSchema_xdecoratorprops.params) ? void 0 : _fieldSchema_xdecoratorprops_params.sort) || [];
    const collectionFieldSchema = recursiveParent(fieldSchema, 'CollectionField');
    const collectionField = getCollectionJoinField(null == collectionFieldSchema ? void 0 : collectionFieldSchema['x-collection-field']);
    const sort = null == defaultSort ? void 0 : defaultSort.map((item)=>item.startsWith('-') ? {
            field: item.substring(1),
            direction: 'desc'
        } : {
            field: item,
            direction: 'asc'
        });
    const template = useSchemaTemplate();
    const collection = useCollection_deprecated();
    const { dragSort } = field.decoratorProps;
    const record = useRecord();
    const variables = useVariables();
    const { currentFormCollection } = useContext(RecordPickerContext);
    const localVariables = useLocalVariables({
        collectionName: currentFormCollection
    });
    return /*#__PURE__*/ jsxs(GeneralSchemaDesigner, {
        template: template,
        title: title || name,
        disableInitializer: true,
        children: [
            /*#__PURE__*/ jsx(SchemaSettingsDataScope, {
                defaultFilter: (null == fieldSchema ? void 0 : null == (_fieldSchema_xdecoratorprops1 = fieldSchema['x-decorator-props']) ? void 0 : null == (_fieldSchema_xdecoratorprops_params1 = _fieldSchema_xdecoratorprops1.params) ? void 0 : _fieldSchema_xdecoratorprops_params1.filter) || {},
                form: form,
                onSubmit: (param)=>{
                    let { filter } = param;
                    var _service_params;
                    filter = removeNullCondition(filter);
                    const params = field.decoratorProps.params || {};
                    params.filter = filter;
                    field.decoratorProps.params = params;
                    fieldSchema['x-decorator-props']['params'] = params;
                    let serviceFilter = lodash.cloneDeep(filter);
                    if (extraFilter) serviceFilter = serviceFilter ? {
                        $and: [
                            extraFilter,
                            serviceFilter
                        ]
                    } : extraFilter;
                    service.run({
                        ...null == (_service_params = service.params) ? void 0 : _service_params[0],
                        filter: serviceFilter,
                        page: 1
                    });
                    dn.emit('patch', {
                        schema: {
                            ['x-uid']: fieldSchema['x-uid'],
                            'x-decorator-props': fieldSchema['x-decorator-props']
                        }
                    });
                },
                collectionName: name,
                dynamicComponent: (props)=>/*#__PURE__*/ jsx(VariableInput, {
                        ...props,
                        form: form,
                        collectionField: props.collectionField,
                        record: record,
                        shouldChange: getShouldChange({
                            collectionField: props.collectionField,
                            variables,
                            localVariables,
                            getAllCollectionsInheritChain
                        }),
                        currentFormCollectionName: currentFormCollection,
                        currentIterationCollectionName: collectionField.collectionName
                    })
            }),
            (null == collection ? void 0 : collection.tree) && (null == collectionField ? void 0 : collectionField.target) === (null == collectionField ? void 0 : collectionField.collectionName) && /*#__PURE__*/ jsx(SchemaSettingsSwitchItem, {
                title: t('Tree table'),
                defaultChecked: true,
                checked: false !== field.decoratorProps.treeTable,
                onChange: (flag)=>{
                    var _service_params;
                    field.form.clearFormGraph("".concat(field.address, ".*"));
                    field.decoratorProps.treeTable = flag;
                    fieldSchema['x-decorator-props'].treeTable = flag;
                    const params = {
                        ...null == (_service_params = service.params) ? void 0 : _service_params[0],
                        tree: flag ? true : null
                    };
                    dn.emit('patch', {
                        schema: fieldSchema
                    });
                    dn.refresh();
                    service.run(params);
                }
            }),
            /*#__PURE__*/ jsx(SetDataLoadingMode, {}),
            !dragSort && /*#__PURE__*/ jsx(SchemaSettingsModalItem, {
                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;
                    var _service_params;
                    const sortArr = sort.map((item)=>'desc' === item.direction ? "-".concat(item.field) : item.field);
                    const params = field.decoratorProps.params || {};
                    params.sort = sortArr;
                    field.decoratorProps.params = params;
                    fieldSchema['x-decorator-props']['params'] = params;
                    dn.emit('patch', {
                        schema: {
                            ['x-uid']: fieldSchema['x-uid'],
                            'x-decorator-props': fieldSchema['x-decorator-props']
                        }
                    });
                    service.run({
                        ...null == (_service_params = service.params) ? void 0 : _service_params[0],
                        sort: sortArr
                    });
                }
            }),
            /*#__PURE__*/ jsx(SchemaSettingsSelectItem, {
                title: t('Records per page'),
                value: (null == (_field_decoratorProps = field.decoratorProps) ? void 0 : null == (_field_decoratorProps_params = _field_decoratorProps.params) ? void 0 : _field_decoratorProps_params.pageSize) || 20,
                options: [
                    {
                        label: '10',
                        value: 10
                    },
                    {
                        label: '20',
                        value: 20
                    },
                    {
                        label: '50',
                        value: 50
                    },
                    {
                        label: '100',
                        value: 100
                    },
                    {
                        label: '200',
                        value: 200
                    }
                ],
                onChange: (pageSize)=>{
                    var _service_params;
                    const params = field.decoratorProps.params || {};
                    params.pageSize = pageSize;
                    field.decoratorProps.params = params;
                    fieldSchema['x-decorator-props']['params'] = params;
                    service.run({
                        ...null == (_service_params = service.params) ? void 0 : _service_params[0],
                        pageSize,
                        page: 1
                    });
                    dn.emit('patch', {
                        schema: {
                            ['x-uid']: fieldSchema['x-uid'],
                            'x-decorator-props': fieldSchema['x-decorator-props']
                        }
                    });
                }
            }),
            /*#__PURE__*/ jsx(SchemaSettingsDivider, {}),
            /*#__PURE__*/ jsx(SchemaSettingsRemove, {
                removeParentsIfNoChildren: true,
                breakRemoveOn: {
                    'x-component': 'Grid'
                }
            })
        ]
    });
};
export { TableSelectorDesigner };
