import { ArrayField, SelectState } from '@wix/bex-core';
import { action, makeObservable, reaction } from 'mobx';

export interface SelectFieldStateParams<V> {
  select: SelectState<V>;
  filter: ArrayField<V>;
}

export class SelectFieldState<V> {
  readonly select;
  readonly filter;

  constructor(params: SelectFieldStateParams<V>) {
    this.select = params.select;
    this.filter = params.filter;

    makeObservable(this, {
      init: action.bound,
      syncSelectedItems: action.bound,
    });

    this.syncSelectedItems();
  }

  syncSelectedItems() {
    const { select, filter } = this;
    select.clear();
    select.finalizeMany(filter.value);
  }

  init() {
    const disposers = [
      reaction(
        () => this.filter.value,
        () => {
          const {
            select: { selectedValues },
            filter,
          } = this;
          if (filter.value !== selectedValues) {
            this.syncSelectedItems();
          }
        },
      ),
      reaction(
        () => this.select.selectedValues,
        () => {
          const {
            select: { selectedValues },
            filter,
          } = this;
          if (filter.value !== selectedValues) {
            filter.setValue(selectedValues, {
              emitEvents: ['change', 'beforeRefresh', 'refresh'],
            });
          }
        },
      ),
    ];

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