import { ReactElement, createElement } from 'react';
import { WixPatternsContainer, HostContainerExtension } from '@wix/bex-core';
import { computed, makeObservable } from 'mobx';
import { ExtensionsState } from './ExtensionsState';

export interface ExtensionMenuItemsStateParams {
  containerId?: string;
  containerProps?: Record<string, any>;
  container: WixPatternsContainer;
}

export interface ExtensionMenuItem {
  biName?: string;
  dataHook: string;
  prefixIcon?: ReactElement;
  text: string;
  type: 'TPA';
  appId?: string;
  componentId: string;
  onClick: (params?: Record<string, any>) => void;
}

export class ExtensionMenuItemsState {
  readonly _extensionsState: ExtensionsState;

  constructor(params: ExtensionMenuItemsStateParams) {
    this._extensionsState = new ExtensionsState(params);

    makeObservable(this, {
      menuItems: computed,
    });
  }

  get menuItems(): ExtensionMenuItem[] {
    return this._extensionsState.items
      .filter((item): item is Required<HostContainerExtension> => {
        return Boolean(
          item.title &&
            item.menuItem?.IconComponent &&
            item.menuItem?.structuredAction,
        );
      })
      .map((extension) => {
        const {
          componentId,
          appId,
          menuItem: { IconComponent, structuredAction },
        } = extension;

        return {
          biName: extension.title || `menu-item-extension-${componentId}`, // extension.title was requested explicitly by BI, it's not a mistake
          dataHook: `menu-item-extension-${componentId}`,
          prefixIcon: IconComponent && createElement(IconComponent),
          text: extension.title,
          onClick: structuredAction,
          appId,
          componentId,
          type: 'TPA',
        };
      });
  }

  get containerProps() {
    return this._extensionsState._containerProps;
  }

  init() {
    return this._extensionsState.init();
  }
}
