import { action, reaction } from 'mobx';
import { History, replaceSearchParamsWith } from '@wix/bex-core';

export interface ViewsHistoryStateParams {
  views: {
    _initialViewIdFromUrl?: string | null;
    currentView: {
      id: string;
    } | null;
  };
  history: History;
}

export class ViewsHistoryState {
  readonly views;
  readonly history;

  viewIdSearchParamName = 'viewId';

  constructor(params: ViewsHistoryStateParams) {
    this.views = params.views;
    this.history = params.history;

    this._preInitHistoryPersistence();
  }

  _preInitHistoryPersistence() {
    const { history, views } = this;

    const searchParams = new URLSearchParams(history.location.search);

    const viewIdFromUrl = searchParams.get(this.viewIdSearchParamName);

    if (viewIdFromUrl) {
      views._initialViewIdFromUrl = viewIdFromUrl;
    }
  }

  init = action(() => {
    const { views, history } = this;
    const disposers = [
      reaction(
        () => views.currentView,
        (currentView) => {
          replaceSearchParamsWith(history, (searchParams) => {
            if (currentView) {
              searchParams.set(this.viewIdSearchParamName, currentView.id);
            } else {
              searchParams.delete(this.viewIdSearchParamName);
            }
          });
        },
        {
          fireImmediately: true,
        },
      ),
    ];

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