import { ToolbarCollectionState } from '../../state';
import { FiltersMap, ValueBox, withoutDefaults } from '@wix/bex-core';
import { cairoFiltersPanelUsed } from '@wix/bex-core/bi';
import { action, computed, makeObservable } from 'mobx';
import { ReactNode, RefObject, createRef } from 'react';
import { FilterElement } from './filterElement';
import { Button } from '@wix/design-system';

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

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

  readonly panelTitle = new ValueBox<ReactNode>(undefined);
  readonly totalInlineFilters = new ValueBox<number | null>(null);
  readonly filterElements = new ValueBox<FilterElement[]>([]);
  readonly moreFiltersButtonRef: RefObject<Button> =
    createRef<Button>();

  onClearButtonClicked?: () => unknown;

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

    makeObservable(this, {
      panelFilterElements: computed,
      panelFilters: computed,
    });
  }

  get panelFilterElements() {
    const {
      totalInlineFilters: { value: totalInlineFilters },
      filterElements: { value: filterElements },
    } = this;
    return totalInlineFilters != null
      ? filterElements.slice(totalInlineFilters)
      : [];
  }

  get panelFilters() {
    return this.panelFilterElements.map((element) => element.props.filter);
  }

  onFiltersButtonClick = action(() => {
    const actionStartTime = performance.now();
    const { reportBi } = this.toolbar;

    const isOpened = this.toolbar.panels.toggleSidePanel('filters');
    // to be called after the panel is opened/closed and call stack is cleared
    window.setTimeout(() => {
      reportBi(
        withoutDefaults(cairoFiltersPanelUsed)({
          ...this.toolbar._commonDynamicBiParams(),
          isOpened,
          origin: 'Filter Button',
          feature: 'Filter',
          timeFromAction: Math.round(performance.now() - actionStartTime),
        }),
      );
    });
  });
}
