import { action, makeObservable, observable, runInAction, } from 'mobx';
import { TaskState } from './TaskState';
import { cairoCtaClicked, cairoItemSelectionToggled, cairoSearchResults, componentDismissed, loadEnd, loadMore, newItemCreationEnd, pickerModalUsability, pickerPickModalCtaButtonClickOrImmediateCta, } from '@wix/bex-utils/@wix/bi-logger-os-data/v2';
import { withoutIrrelevant } from '../util';
import { Snapshot } from './snapshot';
import { MultiCollectionSupport } from './MultiCollectionSupport';
import { onItemsCreated } from './onItemsCreated';
const DEFAULT_FLOATING_NOTIFICATION_HEIGHT = 54;
const withoutDefaults = withoutIrrelevant();
export class PickerState {
    constructor(params) {
        this.initTask = new TaskState();
        this.floatingNotificationHeight = 0;
        this.onNewPage = () => {
            const { reportBi } = this;
            const startTime = performance.now();
            return ({ totalNewItems }) => {
                reportBi(withoutDefaults(loadMore)({
                    ...this._commonDynamicBiParams(),
                    loadingTime: Math.round(performance.now() - startTime),
                    loadedItems: totalNewItems,
                }));
            };
        };
        this.onSearchStart = () => {
            const { collection, reportBi } = this;
            const { result } = collection;
            const startTime = performance.now();
            reportBi(pickerModalUsability({
                ...this._commonDynamicBiParams(),
                action: 'search',
                searchTerm: collection.query.search.value,
            }));
            return () => {
                reportBi(cairoSearchResults({
                    ...this._commonDynamicBiParams(),
                    loadingTime: Math.round(performance.now() - startTime),
                    searchResultsCnt: result.total,
                    searchTerm: collection.query.search.value,
                }));
            };
        };
        this._onButtonClick = ({ ctaName, currentLevel, numLevels, }) => {
            this.reportBi(cairoCtaClicked({
                ...this._commonDynamicBiParams(),
                ctaIndex: 1,
                numCtas: 1,
                currentLevel,
                numLevels,
                location: 'picker',
                moreActionsIndex: 0,
                ctaName,
                url: typeof window !== 'undefined' ? window.location.href : '',
            }));
        };
        this.onCreateNew = action(async (items) => {
            if (items) {
                await onItemsCreated(this.collection, {
                    items,
                    reportBi: (reportProps) => {
                        this.reportBi({
                            ...reportProps,
                            params: {
                                ...this._commonDynamicBiParams(),
                                ...reportProps.params,
                            },
                        });
                    },
                });
            }
            else {
                runInAction(() => {
                    this.reportBi(newItemCreationEnd({
                        ...this._commonDynamicBiParams(),
                        numSelectedItems: this.collection.bulkSelect.select.selectedCount,
                        resultType: 'dismissed',
                    }));
                });
            }
        });
        this.getMaxItems = params.getMaxItems;
        this.collection = params.collection;
        this.reportBi = params.reportBi;
        this.multi = new MultiCollectionSupport({
            collections: [this.collection],
        });
        this.shouldFilterNotAffectTotalCount =
            params.shouldFilterNotAffectTotalCount ?? (() => false);
        this.isScrollTop = true;
        this.minContentHeight = params.minContentHeight ?? 300;
        this.events = params.events ?? {};
        this.loadStartTime = params.loadStartTime ?? performance.now();
        this.filteredListSize = new Snapshot({
            expression: () => Object.values(this.collection.query.customFilters).map((f) => f?.value),
            effect: () => this.collection.result.total,
        });
        makeObservable(this, {
            setFloatingNotificationHeight: action,
            toggle: action,
            updateIsScrollTop: action,
            onPrimaryButtonClick: action,
            isScrollTop: observable.ref,
        });
    }
    async clearResultAndMoveToStart({ force } = {}) {
        await Promise.all([
            this.collection.clearResultAndMoveToStart({ force }),
        ]);
    }
    updateIsScrollTop(newValue) {
        this.isScrollTop = newValue;
    }
    _commonDynamicBiParams() {
        const { collection, filteredListSize } = this;
        return {
            ...collection._commonDynamicBiParams(),
            listSize: collection.result.total,
            filteredListSize: filteredListSize.value,
            maxItems: this.getMaxItems(),
        };
    }
    init() {
        const { collection, initTask, events: { onReady, onInitialFetchError }, reportBi, filteredListSize, } = this;
        collection.emitter.on('newPageStart', this.onNewPage);
        collection.emitter.on('searchStart', this.onSearchStart);
        const disposers = [
            collection.init(),
            filteredListSize.init(),
        ];
        initTask.runOnce(async () => {
            const { result, query } = collection;
            try {
                await Promise.all([
                    collection.initTask.status.promise,
                ]);
                filteredListSize.forceUpdate();
                runInAction(() => {
                    try {
                        reportBi(withoutDefaults(loadEnd)({
                            ...this._commonDynamicBiParams(),
                            url: typeof window !== 'undefined' ? window.location.href : '',
                            route: typeof window !== 'undefined' ? window.location.pathname : '',
                            loadingTime: Math.round(performance.now() - this.loadStartTime),
                            initialItems: result.size,
                        }));
                        onReady?.({
                            query: query.asComputed,
                            result: result.asComputed,
                        });
                    }
                    catch (e) {
                        collection.errorMonitor.captureException(e);
                    }
                });
            }
            catch (err) {
                await onInitialFetchError?.({
                    err,
                    isOnline: collection.onlineState.isOnline,
                });
                throw err;
            }
        });
        return () => {
            collection.emitter.off('newPageStart', this.onNewPage);
            collection.emitter.off('searchStart', this.onSearchStart);
            for (const disposer of disposers) {
                disposer();
            }
        };
    }
    onCloseButtonClick() {
        const { reportBi } = this;
        reportBi(withoutDefaults(componentDismissed)({
            origin: 'X button',
        }));
    }
    onBackButtonClick() {
        const { _onButtonClick } = this;
        _onButtonClick({ ctaName: 'back', numLevels: 2, currentLevel: 2 });
    }
    onContinueButtonClick() {
        const { _onButtonClick } = this;
        _onButtonClick({ ctaName: 'continue-next', numLevels: 2, currentLevel: 1 });
    }
    onSecondaryButtonOnClick() {
        const { reportBi } = this;
        reportBi(withoutDefaults(componentDismissed)({
            origin: 'Cancel button',
        }));
    }
    onPrimaryButtonClick({ currentLevel, numLevels, }) {
        const { collection: { bulkSelect }, _onButtonClick, reportBi, } = this;
        const { selectedCount } = bulkSelect;
        _onButtonClick({ ctaName: 'continue', currentLevel, numLevels });
        reportBi(pickerPickModalCtaButtonClickOrImmediateCta({
            ...this._commonDynamicBiParams(),
            isImmediate: false,
            itemsCnt: selectedCount,
        }));
    }
    toggle(keyedItem, options = {}) {
        const { collection, events: { onItemSelectClick }, reportBi, } = this;
        const { bulkSelect, query: { search }, } = collection;
        const { select, selectedCountOrTotal: numItemsBefore } = bulkSelect;
        const { selectedValues: [prevSelected], } = select;
        if (options.clear) {
            bulkSelect.select.clear();
        }
        bulkSelect.toggle(keyedItem);
        reportBi(cairoItemSelectionToggled({
            ...this._commonDynamicBiParams(),
            url: typeof window !== 'undefined' ? window.location.href : '',
            isSelectAll: false,
            isFromSearch: !search.isEmpty,
            searchQuery: search.value,
            itemIndex: keyedItem.index,
            numLevels: options.hasAdditionalStep ? 2 : 1,
            itemId: keyedItem.key,
            clickType: bulkSelect.isChecked(keyedItem.key)
                ? 'Selection'
                : 'Deselection',
            numItemsBefore,
            numItemsAfter: bulkSelect.selectedCountOrTotal,
        }));
        onItemSelectClick?.({
            item: keyedItem.item,
            index: keyedItem.index,
            previousIndex: prevSelected != null
                ? bulkSelect.getCollectionItem(prevSelected.key)?.index
                : null,
        });
    }
    setFloatingNotificationHeight(floatingNotificationHeight = DEFAULT_FLOATING_NOTIFICATION_HEIGHT) {
        this.floatingNotificationHeight = floatingNotificationHeight;
    }
}
//# sourceMappingURL=PickerState.js.map