"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FloatingFilterValues = exports.useDistinctFilterColumnValues = void 0;
const tslib_1 = require("tslib");
const React = tslib_1.__importStar(require("react"));
const react_1 = require("react");
const AdaptableContext_1 = require("../../../AdaptableContext");
const ListBoxFilterForm_1 = require("../../FilterForm/ListBoxFilterForm");
const renderSingleValue = (option) => {
    return option.label;
};
const renderMultipleValues = (values, options) => {
    const { focused, placeholder } = options;
    const text = values.map(renderSingleValue).join(', ');
    return values.length ? (React.createElement(React.Fragment, null,
        React.createElement("span", { "data-name": "multiple-values-count" },
            "(",
            values.length,
            ")"),
        " ",
        text)) : focused ? null : (placeholder ?? 'Select...');
};
function useDistinctFilterColumnValues(options) {
    const { columnId, searchValueRef } = options;
    const { api } = (0, AdaptableContext_1.useAdaptable)();
    const [valuesLoadTrigger, setValuesLoadTrigger] = React.useState(0);
    const usePreviousValuesProbablyBecauseOfAGGridUnnecessaryFilterRemountRef = React.useRef(false);
    const triggerValuesLoad = React.useCallback((options) => {
        usePreviousValuesProbablyBecauseOfAGGridUnnecessaryFilterRemountRef.current =
            !!options?.usePrevious;
        setValuesLoadTrigger((prev) => prev + 1);
    }, []);
    const [quickFilterValues, setQuickFilterValues] = React.useState({
        values: [],
        dataLoadIsComplete: false,
        skipDefaultSearch: false,
        searchValueUsedInFilterValue: false,
    });
    const [isDistinctColumnValuesLoading, setIsDistinctColumnValuesLoading] = React.useState(false);
    (0, react_1.useEffect)(() => {
        if (valuesLoadTrigger === 0) {
            // skip the first render
            return;
        }
        let ignore = false;
        setIsDistinctColumnValuesLoading(true);
        let searchValueUsedInFilterValue = false;
        const columnFilterinternalApi = api.filterApi.columnFilterApi.internalApi;
        let promise = undefined;
        if (usePreviousValuesProbablyBecauseOfAGGridUnnecessaryFilterRemountRef.current) {
            const previousResult = columnFilterinternalApi
                .getAdaptableFilterHandler(columnId)
                ?.getLastCachedFilterDisplayValues();
            if (previousResult) {
                promise = Promise.resolve(previousResult);
            }
        }
        usePreviousValuesProbablyBecauseOfAGGridUnnecessaryFilterRemountRef.current = false;
        if (!promise) {
            promise = columnFilterinternalApi.getColumnFilterValues({
                columnId,
                get currentSearchValue() {
                    searchValueUsedInFilterValue = true;
                    return searchValueRef ? searchValueRef.current : '';
                },
            });
        }
        promise.then((distinctFilterDisplayValues) => {
            if (ignore) {
                return;
            }
            const values = distinctFilterDisplayValues.values;
            setQuickFilterValues({
                values,
                dataLoadIsComplete: true,
                skipDefaultSearch: !!distinctFilterDisplayValues.skipDefaultSearch,
                searchValueUsedInFilterValue,
            });
            setIsDistinctColumnValuesLoading(false);
        });
        return () => {
            ignore = true;
        };
    }, [valuesLoadTrigger, columnId]);
    return {
        isDistinctColumnValuesLoading,
        quickFilterValues,
        setQuickFilterValues,
        triggerValuesLoad,
    };
}
exports.useDistinctFilterColumnValues = useDistinctFilterColumnValues;
/**
 * This component was ported and modified to not know about colum  filter and predicates.
 * It should be further refactored to be easily ported;
 */
const FloatingFilterValues = (props) => {
    const { api } = (0, AdaptableContext_1.useAdaptable)();
    const currentColumn = api.columnApi.getColumnWithColumnId(props.columnId);
    const searchValueRef = React.useRef('');
    const { isDistinctColumnValuesLoading, quickFilterValues, triggerValuesLoad } = useDistinctFilterColumnValues({
        columnId: props.columnId,
        searchValueRef,
    });
    const valueRef = React.useRef(props.value);
    (0, react_1.useEffect)(() => {
        // we used to load values initially on mount, without any condition
        const value = valueRef.current;
        // but we now optimize it - if there are no values to show (for which we would need a label)
        // then we skip it altogether, so we'll only load onMenuOpen
        if (!value || !Array.isArray(value) || value.length === 0) {
            return;
        }
        // see 😅 usePreviousValuesProbablyBecauseOfAGGridUnnecessaryFilterRemountRef 😅
        const usePrevious = !!api.filterApi.columnFilterApi.internalApi
            .getAdaptableFilterHandler(props.columnId)
            ?.getLastCachedFilterDisplayValues();
        // however, if the `value` prop is a non-empty array, we need to load the values
        // so we know which labels to show
        triggerValuesLoad({
            usePrevious,
        });
    }, []);
    const quickFilterValuesRef = React.useRef(quickFilterValues);
    quickFilterValuesRef.current = quickFilterValues;
    (0, react_1.useEffect)(() => {
        // since we did the optimization above,
        // we now hit a scenario where the value is set via an API method
        // so we also need to account for that - so whenever props.value changes, we need to check
        // and if we previously didn't have a valid array
        // and now we do, we need to load the values - if they are not already loaded
        if (quickFilterValuesRef.current.values.length > 0 ||
            quickFilterValuesRef.current.dataLoadIsComplete) {
            // values have already been loaded, so we can skip
            return;
        }
        const currentValue = props.value;
        const prevValue = valueRef.current;
        valueRef.current = currentValue;
        const prevValid = Array.isArray(prevValue) && prevValue.length > 0;
        const currentValid = Array.isArray(currentValue) && currentValue.length > 0;
        if (!currentValid) {
            return;
        }
        if (!prevValid && currentValid) {
            triggerValuesLoad();
        }
    }, [props.value]);
    const onMenuOpen = triggerValuesLoad;
    const onInputChange = React.useCallback((value) => {
        searchValueRef.current = value;
        const quickFilterValues = quickFilterValuesRef.current;
        if (quickFilterValues.searchValueUsedInFilterValue || quickFilterValues.skipDefaultSearch) {
            triggerValuesLoad();
        }
    }, []);
    const { skipDefaultSearch } = quickFilterValues;
    return (React.createElement(ListBoxFilterForm_1.ColumnValuesSelect, { selectProps: props.inline
            ? {
                ...props.selectProps,
                'data-name': 'Select Values',
                renderMultipleValues,
                isClearable: false,
                skipDefaultFiltering: skipDefaultSearch,
                styles: {
                    dropdownIndicator: {
                        display: 'none',
                    },
                    container: {
                        height: '100%',
                        fontWeight: 'normal',
                    },
                    control: {
                        height: '100%',
                        borderRadius: 'none',
                        border: 'none',
                        // @ts-ignore ignore
                        '&:hover': {
                            border: 'none',
                        },
                    },
                    ...(props.value?.length
                        ? {
                            valueContainer: {
                                fontWeight: 'var(--ab-cmp-quickfilter-selected-options-text__font-weight)',
                            },
                        }
                        : {}),
                },
                onMenuOpen,
                onInputChange,
            }
            : {
                ...props.selectProps,
                skipDefaultFiltering: skipDefaultSearch,
                onMenuOpen,
                onInputChange,
            }, disabled: props.disabled, isLoading: isDistinctColumnValuesLoading, column: currentColumn, dataType: currentColumn.dataType, options: quickFilterValues.values, value: props.value, onChange: props.onChange }));
};
exports.FloatingFilterValues = FloatingFilterValues;
