import {
  useComponentInfo,
  useErrorHandler,
  useHttpClient,
  useModuleInfo,
  useModuleParams,
} from '@wix/yoshi-flow-bm';
import React, { useState } from 'react';
import { CairoProvider } from '../providers';
import { buildBMCairoEssentials } from './buildBMCairoEssentials';
import { useErrorMonitorCompat } from './errorMonitorCompat';
import { showToastCompat, WixPatternsEssentialsOverrides } from '@wix/bex-core';
import { useExperimentsCompat } from './useExperimentsCompat';
import { usePlatformApiCompat } from './usePlatformApiCompat';
import { minimalRequiredRuntimeCheck } from '../utils/minimalRequiredRuntimeCheck';
import { usePageLocation, CairoProviderBaseProps } from '@wix/bex-core/react';

export interface WixPatternsBMProviderProps
  extends Omit<CairoProviderBaseProps, 'contextType'> {
  overrides?: Partial<WixPatternsEssentialsOverrides>;
}

export function WixPatternsBMProvider(props: WixPatternsBMProviderProps) {
  const { overrides, children } = props;
  if (process.env.NODE_ENV !== 'production') {
    minimalRequiredRuntimeCheck({
      packageJson: require('@wix/yoshi-flow-bm/package.json'),
      required: '^6.103.0',
    });
  }

  const moduleParams = useModuleParams();

  const moduleInfo = useModuleInfo();
  const componentInfo = useComponentInfo();

  const errorMonitor = useErrorMonitorCompat();

  const httpClient = useHttpClient();
  const errorHandler = useErrorHandler();

  const experiments = useExperimentsCompat();
  const { onBeforeUnload, showToast } = usePlatformApiCompat();

  const [wixPatternsEssentialsOverrides] = useState(
    (): Partial<WixPatternsEssentialsOverrides> => ({
      onBeforeUnload,
      errorHandler: errorHandler.v2,
      showToast: showToast ? showToastCompat(showToast) : undefined,
      usePageLocation,
      ...overrides,
    }),
  );

  const [wixPatternsEssentials] = useState(() => {
    const flowAPI = {
      errorMonitor,
      httpClient,
      componentInfo,
      moduleInfo,
      moduleParams,
      experiments,
    };

    return buildBMCairoEssentials(flowAPI, {
      overrides: wixPatternsEssentialsOverrides,
    });
  });

  return (
    <CairoProvider {...props} value={wixPatternsEssentials}>
      {children}
    </CairoProvider>
  );
}
