import { withoutDefaults, } from '@wix/bex-core';
import { cairoFilterToggled } from '@wix/bex-core/bi';
import { action, computed, makeObservable } from 'mobx';
import { EventEmitter } from 'events';
import { addEventListener } from '@wix/bex-core/util';
import groupBy from 'lodash/groupBy';
import { FilterTagContent } from './FilterTagContent';
import React from 'react';
export class AppliedFiltersTagListState {
    constructor(params) {
        this.events = new EventEmitter();
        this.maxWidth = '408px';
        this.onClearButtonClick = action(() => {
            const { table } = this;
            const { collection, toolbarFiltersState } = table;
            const { query: { nonPersistentFilters }, } = collection;
            collection.emitter.emit('beforeClearFilters', { origin: 'toolbar' });
            nonPersistentFilters
                .filter((filter) => !filter._hideFromToolbar)
                .forEach((filter) => {
                filter?.reset({ emitEvents: ['change', 'refresh'] });
            });
            toolbarFiltersState?.moreFiltersButtonRef?.current?.focus();
        });
        this.table = params.table;
        makeObservable(this, {
            filterValues: computed,
            tags: computed,
            filterPropsMap: computed,
        });
    }
    init() {
        const { multi: { collections }, } = this.table;
        const disposers = [
            ...collections.map((collection) => addEventListener(collection.emitter, 'fetch', () => {
                const ls = this.events.listeners('fetch').map((l) => l(collection));
                return () => {
                    ls.forEach((l) => l());
                };
            })),
        ];
        return () => {
            disposers.forEach((d) => d());
        };
    }
    get filterPropsMap() {
        const { table: { filtersProps }, } = this;
        return new Map(filtersProps?.map((filterProps) => [filterProps.filter, filterProps]) ??
            []);
    }
    toTag(key, filter) {
        const { filterPropsMap } = this;
        const { value: filterValue } = filter;
        const explodeTags = filterPropsMap.get(filter)?.explodeTags;
        return filter.toArray.map((value) => ({
            id: Array.isArray(filterValue) || explodeTags
                ? `${key}-${filter.itemKey(value)}`
                : key,
            filter,
            value,
        }));
    }
    get filterValues() {
        const { table: { activeFiltersEntries }, } = this;
        return activeFiltersEntries
            .filter(([_, filter]) => !filter._hideFromToolbar)
            .flatMap(([key, filter]) => this.toTag(key, filter));
    }
    get tags() {
        const { filterValues, filterPropsMap } = this;
        const groupedFilters = groupBy(filterValues, 'filter.name');
        return Object.entries(groupedFilters).flatMap(([_, filterValuesGroup]) => {
            const filterProps = filterPropsMap.get(filterValuesGroup[0].filter);
            if (filterProps?.renderToolbarTag) {
                return this.generateNonAggregatedTag(filterValuesGroup, filterProps);
            }
            return this.generateAggregatedTag(filterValuesGroup, filterProps);
        });
    }
    _reportFilterToggleBiOnNextResult(filter, values) {
        const filterValuesKeys = values.map((value) => filter.itemKey(value));
        const { table, events } = this;
        const { reportBi } = table;
        const onFetch = (collection) => {
            events.off('fetch', onFetch);
            return action(() => {
                reportBi(withoutDefaults(cairoFilterToggled)({
                    ...table._commonDynamicBiParams(),
                    ...collection._commonDynamicBiParams(),
                    actionType: 'remove',
                    origin: 'sub-toolbar',
                    filterName: filter.name,
                    filterValue: filterValuesKeys.join(),
                    numFiltersActive: collection.query.activeFiltersCount,
                    filteredListSize: collection.result.total,
                    isCustomField: !!filter.isCustomField,
                }));
            });
        };
        events.on('fetch', onFetch);
    }
    onTagRemove(filter, values, onAppliedFilterTagRemove) {
        const { table, tags } = this;
        const isLastTag = tags.length === 1;
        this._reportFilterToggleBiOnNextResult(filter, values);
        filter.remove(values, {
            emitEvents: ['change', 'refresh'],
        });
        values.forEach((value) => {
            onAppliedFilterTagRemove?.(value);
        });
        if (isLastTag) {
            table.toolbarFiltersState?.moreFiltersButtonRef?.current?.focus();
        }
    }
    generateNonAggregatedTag(filterValuesGroup, filterProps) {
        return filterValuesGroup.map(({ id, filter, value }) => {
            return {
                children: filter.itemName(value),
                key: id,
                filterProps,
                id,
                dataHook: id,
                filter,
                values: [value],
                maxWidth: this.maxWidth,
                ...filterProps?.renderToolbarTag?.(value),
            };
        });
    }
    generateAggregatedTag(filterValuesGroup, filterProps) {
        return {
            children: (React.createElement(FilterTagContent, { filterProps: filterProps }, filterValuesGroup
                .map(({ filter, value }) => filter.itemName(value))
                .join(', '))),
            key: filterProps?.filter.name,
            filterProps,
            id: filterProps?.filter.name,
            dataHook: filterProps?.filter.name,
            filter: filterValuesGroup[0].filter,
            values: filterValuesGroup.map(({ value }) => value),
            maxWidth: this.maxWidth,
        };
    }
}
//# sourceMappingURL=AppliedFiltersTagListState.js.map