import { action, makeObservable, observable } from 'mobx';
import { EventEmitter } from 'events';
import { TypedEmitter } from '@wix/bex-core/events';
import React from 'react';
import type { AutoComplete } from '@wix/design-system';

export class AutoCompleteReadonlyState {
  disableEditing = true;
  isFocused = false;
  clearInput?: () => void;
  autoCompleteRef?: React.RefObject<typeof AutoComplete.prototype | null>;

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

  constructor() {
    makeObservable(this, {
      disableEditing: observable.ref,
    });
  }

  focusInput = action(() => {
    this.disableEditing = false;
    setTimeout(() => {
      this.autoCompleteRef?.current?.focus();
    }, 0);
  });

  onFocus = action(() => {
    this.isFocused = true;
    this.disableEditing = false;
  });

  onBlur = action(() => {
    this.isFocused = false;
    this.events.emit('blur');
    // verify that eventually disableEditing=true if isFocused=false
    // not doing this immediately not to hide `inputClearButton` too soon when it's clicked
    window.setTimeout(
      action(() => {
        if (!this.isFocused) {
          this.disableEditing = true;
          this.clearInput?.();
        }
      }),
      300,
    );
  });

  onItemClick = action(() => {
    this.disableEditing = true;
  });

  onClickOutside = action(() => {
    this.disableEditing = true;
    this.clearInput?.();
  });

  onInputClearButtonClick = action(() => {
    this.clearInput?.();
  });

  onTabKeyDown = action(() => {
    this.disableEditing = true;
    this.clearInput?.();
  });

  onSelect = action(() => {
    this.disableEditing = true;
  });

  onOptionsShow = action(() => {
    this.disableEditing = false;
  });
}
