import { action, computed, makeObservable, observable } from 'mobx';
import { ActionSubitem } from '../ActionControl/ActionSubItemProps';
import { ExtensionMenuItemsState } from '../../state/ExtensionMenuItemsState';
import { MoreActionsItem } from '../MoreActions';
import { CollectionState, FiltersMap } from '@wix/bex-core';

export interface MultiBulkActionToolbarStateParams<T, F extends FiltersMap> {
  collection: CollectionState<T, F>;
  extensionMenuItems: ExtensionMenuItemsState;
}

export class MultiBulkActionToolbarState<T, F extends FiltersMap> {
  _primaryActionItems: ActionSubitem[] = [];
  _secondaryActionItems: ActionSubitem[][] = [];

  _extensionMenuItems: ExtensionMenuItemsState;
  _collection: CollectionState<T, F>;

  constructor(props: MultiBulkActionToolbarStateParams<T, F>) {
    const { collection, extensionMenuItems } = props;

    this._collection = collection;
    this._extensionMenuItems = extensionMenuItems;

    makeObservable(this, {
      _primaryActionItems: observable.ref,
      _secondaryActionItems: observable.ref,
      setActions: action,
      primaryActionItems: computed,
      secondaryActionItems: computed,
      secondaryActionItemsCount: computed,
    });
  }

  setActions({
    primaryActionItems = [],
    secondaryActionItems = [],
  }: {
    actionItems?: ActionSubitem[];
    primaryActionItems?: ActionSubitem[];
    secondaryActionItems?: ActionSubitem[] | ActionSubitem[][];
  }) {
    this._primaryActionItems = primaryActionItems.map((item) => ({
      ...item,
      subItems: item.subItems
        ? Array.isArray(item.subItems?.[0])
          ? (item.subItems as ActionSubitem[][])
          : [item.subItems as ActionSubitem[]]
        : item.subItems,
    }));
    this._secondaryActionItems = Array.isArray(secondaryActionItems?.[0])
      ? (secondaryActionItems as ActionSubitem[][])
      : [secondaryActionItems as ActionSubitem[]];
  }

  private _moreActionItemClick(item: MoreActionsItem) {
    const {
      result: { total },
      bulkSelect,
    } = this._collection;

    const { selectedIds, uncheckedIds, allSelected } = bulkSelect;

    item.onClick({
      selectedIds,
      uncheckedIds,
      isSelectAll: allSelected,
      total,
      ...this._extensionMenuItems.containerProps,
    });
  }

  get primaryActionItems() {
    return this._primaryActionItems;
  }

  get secondaryActionItems(): ActionSubitem[][] {
    const moreActionItems: ActionSubitem[] =
      this._extensionMenuItems.menuItems.map((item) => ({
        ...item,
        label: item.text,
        onClick: () => this._moreActionItemClick(item),
      })) || [];

    return [...this._secondaryActionItems, moreActionItems];
  }

  get secondaryActionItemsCount() {
    return this.secondaryActionItems.reduce(
      (result, group) => result + group.length,
      0,
    );
  }
}
