import { jsx } from "react/jsx-runtime";
import react, { createContext, useCallback, useEffect, useRef } from "react";
import { useField, useFieldSchema } from "@tachybase/schema";
import { uniqBy } from "lodash";
import { useBlockRequestContext } from "../block-provider/BlockProvider.mjs";
import { useCollection_deprecated } from "../collection-manager/index.mjs";
import { useDataLoadingMode } from "../modules/blocks/data-blocks/details-multi/setDataLoadingModeSettingsItem.mjs";
import { removeNullCondition } from "../schema-component/index.mjs";
import { mergeFilter, useAssociatedFields } from "./utils.mjs";
const FilterContext = /*#__PURE__*/ createContext(null);
FilterContext.displayName = 'FilterContext';
const FilterBlockProvider = (param)=>{
    let { children } = param;
    const [dataBlocks, setDataBlocks] = react.useState([]);
    return /*#__PURE__*/ jsx(FilterContext.Provider, {
        value: {
            dataBlocks,
            setDataBlocks
        },
        children: children
    });
};
const DataBlockCollector = (param)=>{
    let { children, params } = param;
    const collection = useCollection_deprecated();
    const { recordDataBlocks, removeDataBlock } = useFilterBlock();
    const { service } = useBlockRequestContext();
    const field = useField();
    const fieldSchema = useFieldSchema();
    const associatedFields = useAssociatedFields();
    const container = useRef(null);
    const dataLoadingMode = useDataLoadingMode();
    const shouldApplyFilter = 'FilterFormBlockProvider' !== field.decoratorType && 'FormBlockProvider' !== field.decoratorType && 'filter' !== field.decoratorProps.blockType;
    const addBlockToDataBlocks = useCallback(()=>{
        recordDataBlocks({
            uid: fieldSchema['x-uid'],
            title: field.componentProps.title,
            doFilter: service.runAsync,
            collection,
            associatedFields,
            foreignKeyFields: collection.foreignKeyFields,
            defaultFilter: (null == params ? void 0 : params.filter) || {},
            service,
            dom: container.current,
            dataLoadingMode,
            clearFilter (uid) {
                var _this_service_params, _this_service_params_, _this_service_params1;
                const param = (null == (_this_service_params = this.service.params) ? void 0 : _this_service_params[0]) || {};
                const storedFilter = (null == (_this_service_params1 = this.service.params) ? void 0 : null == (_this_service_params_ = _this_service_params1[1]) ? void 0 : _this_service_params_.filters) || {};
                delete storedFilter[uid];
                const mergedFilter = mergeFilter([
                    ...Object.values(storedFilter).map((filter)=>removeNullCondition(filter)),
                    (null == params ? void 0 : params.filter) || {}
                ]);
                this.service.run({
                    ...param,
                    page: 1,
                    filter: mergedFilter
                }, {
                    filters: storedFilter
                });
            },
            clearData () {
                this.service.mutate(void 0);
            }
        });
    }, [
        associatedFields,
        collection,
        dataLoadingMode,
        field,
        fieldSchema,
        null == params ? void 0 : params.filter,
        recordDataBlocks,
        service
    ]);
    useEffect(()=>{
        if (shouldApplyFilter) addBlockToDataBlocks();
    }, [
        params.filter,
        service,
        dataLoadingMode,
        shouldApplyFilter,
        addBlockToDataBlocks
    ]);
    useEffect(()=>()=>{
            removeDataBlock(fieldSchema['x-uid']);
        }, []);
    return /*#__PURE__*/ jsx("div", {
        ref: container,
        children: children
    });
};
const useFilterBlock = ()=>{
    const ctx = react.useContext(FilterContext);
    if (!ctx) return {
        inProvider: false,
        recordDataBlocks: ()=>{},
        getDataBlocks: ()=>[],
        removeDataBlock: ()=>{}
    };
    const { dataBlocks, setDataBlocks } = ctx;
    const recordDataBlocks = (block)=>{
        const existingBlock = dataBlocks.find((item)=>item.uid === block.uid);
        if (existingBlock) {
            existingBlock.service = block.service;
            existingBlock.defaultFilter = block.defaultFilter;
            existingBlock.dataLoadingMode = block.dataLoadingMode;
            return;
        }
        setDataBlocks((prev)=>uniqBy([
                ...prev,
                block
            ], 'uid'));
    };
    const getDataBlocks = ()=>dataBlocks;
    const removeDataBlock = (uid)=>{
        setDataBlocks((prev)=>prev.filter((item)=>item.uid !== uid));
    };
    return {
        recordDataBlocks,
        getDataBlocks,
        removeDataBlock,
        inProvider: true
    };
};
export { DataBlockCollector, FilterBlockProvider, useFilterBlock };
