import { addEventListener } from '@wix/bex-core/util';
import { FiltersMap, withoutIrrelevant } from '@wix/bex-core';
import { cairoItemSelectionToggled } from '@wix/bex-core/bi';
import { PickerContentState } from './PickerContentState';
import { action } from 'mobx';

const withoutDefaults = withoutIrrelevant<
  | 'currentTab'
  | 'currentView'
  | 'currentFilters'
  | 'currentSortOrder'
  | 'listSize'
  | 'filteredListSize'
  | 'maxItems'
  | 'initialItems'
>();

export interface PickerContentStateBIParams<T, F extends FiltersMap> {
  state: PickerContentState<T, F>;
}

export class PickerContentStateBI<T, F extends FiltersMap> {
  state;

  constructor(params: PickerContentStateBIParams<T, F>) {
    this.state = params.state;
  }

  init() {
    const { events } = this.state;

    const disposers = [
      addEventListener(events, 'beforeToggleIsSelectAll', () => {
        const { picker, reportBi } = this.state;
        const {
          collection: {
            bulkSelect,
            query: { search },
          },
        } = picker;

        const numItemsBefore = bulkSelect.selectedCountOrTotal;

        return {
          afterToggleIsSelectAll: action(() => {
            const { allSelected } = bulkSelect;

            reportBi(
              withoutDefaults(cairoItemSelectionToggled)({
                ...picker._commonDynamicBiParams(),
                url: typeof window !== 'undefined' ? window.location.href : '',
                isSelectAll: true,
                isFromSearch: !search.isEmpty,
                searchQuery: search.value,
                itemId: allSelected ? 'All' : undefined,
                clickType: allSelected ? 'Selection' : 'Deselection',
                numItemsBefore,
                numItemsAfter: bulkSelect.selectedCountOrTotal,
              }),
            );
          }),
        };
      }),
    ];

    return () => {
      disposers.forEach((d) => d());
    };
  }
}
