import { ToolbarCollectionState } from '../../state';
import { FiltersMap, withoutDefaults } from '@wix/bex-core';
import { cairoFiltersPanelUsed } from '@wix/bex-core/bi';
import { action, makeObservable, observable } from 'mobx';

export interface FiltersPanelStateParams<T, F extends FiltersMap> {
  readonly toolbar: ToolbarCollectionState<T, F>;
}

export class FiltersPanelState<T, F extends FiltersMap> {
  readonly toolbar;

  searchValue = '';

  constructor(params: FiltersPanelStateParams<T, F>) {
    this.toolbar = params.toolbar;

    makeObservable(this, {
      searchValue: observable.ref,
      setSearchValue: action.bound,
      clearSearch: action.bound,
    });
  }

  setSearchValue(value: string) {
    this.searchValue = value;
  }

  clearSearch() {
    this.searchValue = '';
  }

  onCloseButtonClick = action(async () => {
    const { reportBi, panels, pendingQuery } = this.toolbar;

    const result = await pendingQuery?.onCloseFiltersPanelClick();

    if (result === 'dismissed') {
      return;
    }

    this.clearSearch();

    panels.closeSidePanel();
    reportBi(
      withoutDefaults(cairoFiltersPanelUsed)({
        ...this.toolbar._commonDynamicBiParams(),
        origin: 'X Button',
        isOpened: false,
        feature: 'Filter',
      }),
    );
  });
}
