import { FiltersMap, withoutDefaults } from '@wix/bex-core';
import { ToolbarCollectionState } from '../../state';
import { TabsResponsiveState } from './TabsResponsiveState';
import { EventEmitter } from 'events';
import { TypedEmitter } from '@wix/bex-core/events';
import { addEventListener } from '@wix/bex-core/util';
import { action } from 'mobx';
import { cairoTabSelected } from '@wix/bex-core/bi';

export interface TabsFilterStateParams<T, F extends FiltersMap> {
  readonly table: ToolbarCollectionState<T, F>;
}

type TabsFilterItemBase = {
  id: string;
  index: number;
};

export class TabsFilterState<T, F extends FiltersMap> {
  readonly table;
  readonly responsive: TabsResponsiveState;

  readonly events = new EventEmitter() as TypedEmitter<{
    fetch: () => () => unknown;
  }>;

  constructor(params: Readonly<TabsFilterStateParams<T, F>>) {
    this.table = params.table;
    this.responsive = new TabsResponsiveState({
      container: this.table.container,
    });
  }

  init({
    container,
    itemsCount,
  }: {
    container?: HTMLDivElement;
    itemsCount: number;
  }) {
    const { collection } = this.table;

    const disposers = [
      addEventListener(collection.emitter, 'fetch', () => {
        const ls = this.events.listeners('fetch').map((l) => l());
        return () => {
          ls.forEach((l) => l());
        };
      }),
      this.responsive.init({ container, itemsCount }),
    ];

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

  _reportTabSelectedBiOnNextResult({
    nextTab,
    prevTab,
    items,
    hasAllTab,
  }: {
    prevTab?: TabsFilterItemBase;
    nextTab: TabsFilterItemBase;
    items: TabsFilterItemBase[];
    hasAllTab?: boolean;
  }) {
    const { table, events } = this;
    const { reportBi } = table;

    const onFetch = () => {
      events.off('fetch', onFetch);

      return action(() => {
        reportBi(
          withoutDefaults(cairoTabSelected)({
            ...table._commonDynamicBiParams(),
            newTabIndex: nextTab.index + 1,
            newTabId: nextTab.id,
            prevTabIndex:
              prevTab?.index != null ? prevTab.index + 1 : undefined,
            prevTabId: prevTab?.id,
            numTabs: items.length,
            hasAllTab,
          }),
        );
      });
    };

    events.on('fetch', onFetch);
  }
}
