import {
  CollectionState,
  FiltersMap,
  TaskState,
  WixPatternsContainer,
  WixPatternsContainerParams,
} from '@wix/bex-core';
import { TableState } from './TableState';
import { GridState } from './GridState';
import { computed, makeObservable, runInAction } from 'mobx';
import { ToolbarCollectionState } from './ToolbarCollectionState';
import { ViewTypeState } from './ViewTypeState';
import { ICollectionComponentState } from './ICollectionComponentState';

export interface TableGridSwitchStateParams<T, F extends FiltersMap> {
  readonly collection: CollectionState<T, F>;
  readonly container: WixPatternsContainer;
  readonly containerOverrides: Partial<WixPatternsContainerParams>;
}
type ViewType = 'table' | 'grid';
const componentType = 'TableGridSwitch';
export class TableGridSwitchState<T, F extends FiltersMap>
  implements ICollectionComponentState
{
  collection: CollectionState<T, F>;
  readonly container;
  readonly containerOverrides: Partial<WixPatternsContainerParams>;
  readonly initTask = new TaskState();
  readonly gridState: GridState<T, F>;
  readonly tableState: TableState<T, F>;
  readonly viewTypeState: ViewTypeState;

  constructor(params: TableGridSwitchStateParams<T, F>) {
    this.container = params.container;
    this.containerOverrides = params.containerOverrides;

    this.collection = params.collection;

    this.tableState = new TableState({
      collection: this.collection,
      container: this.container,
      toolbar: new ToolbarCollectionState({
        componentType,
        collection: this.collection,
        container: this.container,
        reportBi: (biParams) =>
          this.container.reportBi({
            ...biParams,
            params: {
              ...biParams.params,
              componentStatus: this.viewTypeState.viewType,
            },
          }),
      }),
    });

    this.gridState = new GridState({
      collection: this.collection,
      container: this.container,
      toolbar: this.tableState.toolbar,
    });

    this.viewTypeState = new ViewTypeState({
      container: this.container,
      dataCapsule: this.toolbar.dataCapsule,
      componentType,
      collection: this.collection,
    });

    makeObservable(this, {
      viewType: computed,
    });
  }

  get viewType() {
    return this.viewTypeState.viewType;
  }

  set viewType(viewType: ViewType) {
    runInAction(() => {
      this.viewTypeState.viewType = viewType;
    });
  }

  get toolbar() {
    return this.tableState.toolbar;
  }

  init() {
    const { viewTypeState, initTask } = this;
    viewTypeState.init();

    initTask.runOnce(async () => {
      viewTypeState.initTask.runOnce();

      await viewTypeState.initTask.status.promise;
    });
  }
}
