import { action, makeObservable, observable } from 'mobx';
import type { CollectionState } from '@wix/bex-core';
import { ConditionalModalState, FiltersMap, KeyedItem } from '@wix/bex-core';
import { MessageModalLayoutProps } from '@wix/design-system';

type Fade = 'static' | 'idle' | 'exit' | 'exiting';

export interface ActionCellAPI<T, F extends FiltersMap> {
  openConfirmModal: (props?: Partial<MessageModalLayoutProps>) => void;
  openConfirmDeleteModal: (props?: Partial<MessageModalLayoutProps>) => void;
  collection: CollectionState<T, F>;
  keyedItem: KeyedItem<T>;
}

export interface ItemActionsStateParams<T, F extends FiltersMap = FiltersMap> {
  fade: Fade;
  keyedItem: KeyedItem<T>;
  collection: CollectionState<T, F>;
}

export class ItemActionsState<T, F extends FiltersMap = FiltersMap> {
  keyedItem: KeyedItem<T>;
  fade: Fade;
  readonly collection: CollectionState<T, F>;

  readonly confirmModal = new ConditionalModalState<
    Partial<MessageModalLayoutProps>
  >();

  readonly actionCellAPI: ActionCellAPI<T, F>;

  constructor(params: ItemActionsStateParams<T, F>) {
    this.fade = params.fade;
    this.keyedItem = params.keyedItem;
    this.collection = params.collection;

    makeObservable(this, {
      keyedItem: observable.ref,
      fade: observable.ref,
      onFadeStart: action.bound,
      onFadeDone: action.bound,
      setItemIfChanged: action,
      openConfirmModal: action.bound,
      openConfirmDeleteModal: action.bound,
    });

    this.actionCellAPI = {
      openConfirmModal: this.openConfirmModal,
      openConfirmDeleteModal: this.openConfirmDeleteModal,
      collection: this.collection,
      keyedItem: this.keyedItem,
    };
  }

  openConfirmModal(props?: Partial<MessageModalLayoutProps>) {
    const { translate: t } = this.collection;
    this.confirmModal.open({
      title: t('cairo.confirmModal.title'),
      primaryButtonText: t('cairo.confirm.button'),
      secondaryButtonText: t('cairo.cancel.button'),
      ...props,
    });
  }

  openConfirmDeleteModal(props?: Partial<MessageModalLayoutProps>) {
    const { translate: t } = this.collection;
    this.openConfirmModal({
      theme: 'destructive',
      title: t('cairo.deleteModal.title'),
      content: t('cairo.deleteModal.body'),
      ...props,
    });
  }

  onFadeStart() {
    if (this.fade === 'exit') {
      this.fade = 'exiting';
    }
  }

  onFadeDone() {
    const { fade } = this;
    if (fade === 'exiting') {
      this.fade = 'idle';
    }
  }

  setItemIfChanged(keyedItem: KeyedItem<T>) {
    if (this.keyedItem !== keyedItem) {
      this.keyedItem = keyedItem;
    }
  }
}
