import {
  WixPatternsContainer,
  TaskState,
  CollectionState,
} from '@wix/bex-core';
import { cairoSectionCtaClicked } from '@wix/bex-core/bi';
import type { Essentials } from '@wix/fe-essentials/core';
import { action, makeObservable, observable, runInAction } from 'mobx';

export interface ViewTypeStateParams {
  readonly container: WixPatternsContainer;
  readonly dataCapsule: Essentials['dataCapsule'];
  readonly componentType: string;
  readonly collection?: CollectionState<any, any>;
}
type ViewType = 'table' | 'grid';

export class ViewTypeState {
  viewType: ViewType = 'table';
  readonly container;
  readonly dataCapsule;
  readonly componentType;
  readonly collection;
  readonly initTask = new TaskState();
  constructor(params: ViewTypeStateParams) {
    this.container = params.container;
    this.dataCapsule = params.dataCapsule;
    this.componentType = params.componentType;
    this.collection = params.collection;

    makeObservable(this, {
      viewType: observable.ref,
      changeViewType: action.bound,
    });
  }

  init() {
    this.initTask.runOnce(async () => {
      await this._getViewTypeFromStorage();
    });
  }

  async _getViewTypeFromStorage() {
    try {
      const res = (await this.dataCapsule.getItem('view-type')) as ViewType;
      runInAction(() => {
        this.viewType = res || this.viewType;
      });
    } catch (err) {
      this.container.errorMonitor.captureException(err);
    }
  }

  changeViewType(newViewType: string) {
    this.container.reportBi(
      cairoSectionCtaClicked({
        ctaType: 'More actions',
        loaction: 'Collection Toolbar',
        location: 'Collection Toolbar',
        componentType: this.componentType,
        sectionType: this.viewType,
        ctaName: `layout switch to ${newViewType}`,
        ...this.collection?._commonDynamicBiParams(),
      }),
    );

    this.viewType = newViewType === 'grid' ? 'grid' : 'table';
    this.dataCapsule.setItem('view-type', newViewType);
  }
}
