import { buildCreateEssentials } from './buildCreateEssentials';
import {
  ComponentHooksFlowAPI,
  FlowBusinessManagerModule,
  Trans,
  useAppLoaded,
  useExperiments,
  useTranslation,
} from '@wix/yoshi-flow-bm';
import {
  closeSidePanel,
  getHostContainer,
  getModule,
  navigateTo,
  onNavigation,
  onSidePanelOpen,
  showToast,
  ToastAction,
  ToastPriority,
  ToastTimeout,
  ToastType,
} from '@wix/business-manager-api';
import {
  createAppSettingsCapsule,
  Experiments,
  GetHostContainer,
  getWixPatternsWindowExperiments,
  WixPatternsEssentials,
  WixPatternsEssentialsOverrides,
} from '@wix/bex-core';
import type { QueryCache } from 'react-query/core';
import type { AppEnvironment } from '@wix/fe-essentials-business-manager/dist/types/types';

export interface FlowAPI {
  moduleParams: ComponentHooksFlowAPI['moduleParams'];
  moduleInfo: ComponentHooksFlowAPI['moduleInfo'];
  componentInfo?: ComponentHooksFlowAPI['componentInfo'];
  errorMonitor: Pick<ComponentHooksFlowAPI['errorMonitor'], 'captureException'>;
  httpClient: ComponentHooksFlowAPI['httpClient'];
  experiments: Experiments;
}

export function buildBMCairoEssentials(
  flowAPI: FlowAPI,
  {
    overrides,
  }: {
    overrides?: Partial<WixPatternsEssentialsOverrides>;
  } = {},
): WixPatternsEssentials {
  const {
    moduleParams,
    moduleInfo,
    componentInfo,
    errorMonitor,
    httpClient,
    experiments,
  } = flowAPI;
  const { accountLanguage: language } = moduleParams;
  const { moduleId } = moduleInfo;
  const componentId = componentInfo?.componentId;

  const bmModule = getModule(moduleId as any) as FlowBusinessManagerModule;
  const _essentials =
    bmModule._essentials as FlowBusinessManagerModule['_essentials'] & {
      env?: Partial<AppEnvironment>;
    };

  const createChildEssentials = buildCreateEssentials(_essentials);

  return {
    createEssentials: (options) => {
      return createChildEssentials({
        ...options,
        experiments:
          options.experiments &&
          'scopes' in options.experiments &&
          options.experiments?.scopes[0] === 'cairo'
            ? {
                bag: getWixPatternsWindowExperiments() ?? {},
              }
            : options.experiments,
      });
    },
    createComponentSettings: createAppSettingsCapsule,
    errorMonitor: errorMonitor ?? { captureException: () => {} },
    useTranslation,
    Trans,
    useExperiments,
    experiments,
    onNavigation,
    onSidePanelOpen,
    getHostContainer: getHostContainer as GetHostContainer,
    closeSidePanel,
    httpClient,
    queryCache: _essentials.UNSAFE_cairoQueryCache as QueryCache,
    navigateTo: (params) => {
      const { pageId, appState, referrer, relativeUrl } = params;

      navigateTo({
        pageComponentId: pageId,
        contextData: { appState: appState || relativeUrl, referrer },
      });
    },
    useAppLoaded: () => {
      useAppLoaded({ auto: true });
    },
    ...overrides,
    showToast:
      overrides?.showToast ??
      (({ type, timeout, priority, action, ...toastConfig }) =>
        showToast({
          ...toastConfig,
          biName: toastConfig.biName ?? '',
          type: type as ToastType,
          priority: priority as ToastPriority,
          action: action as ToastAction,
          ...(timeout && { timeout: timeout as ToastTimeout }),
        })),
    user: {
      permissions: moduleParams.userPermissions,
      ...overrides?.user,
    },
    environment: {
      language,
      componentId,
      artifactId: moduleId,
      ...overrides?.environment,
      providerType: 'bm',
    },
    environmentBI: {
      artifactId: bmModule.artifactId,
      componentId,
    },
  };
}
