import React, { ReactNode, useState } from 'react';
import { showToastCompat, WixPatternsEssentialsOverrides } from '@wix/bex-core';
import { CairoProviderBaseProps, usePageLocation } from '@wix/bex-core/react';
import { useEssentials } from '@wix/yoshi-flow-bm/fe-essentials-giza';
import { useComponentLoaded, usePlatformApi } from '@wix/yoshi-flow-bm';
import { CairoProvider } from '../providers';
import { buildWixPatternsEssentials } from './buildWixPatternsEssentials';
import { minimalRequiredRuntimeCheck } from '../utils/minimalRequiredRuntimeCheck';

export interface WixPatternsGizaProviderProps extends CairoProviderBaseProps {
  children?: ReactNode;
  value?: Partial<WixPatternsEssentialsOverrides>;
}

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

  const {
    children,
    value: wixPatternsEssentialsOverridesProp,
    contextType = 'ACCOUNT',
  } = props;
  const { showToast, navigateTo, onBeforeUnload, getHostContainer } =
    usePlatformApi();

  const essentials = useEssentials();

  const [wixPatternsEssentialsOverrides] = useState(
    (): Partial<WixPatternsEssentialsOverrides> => ({
      usePageLocation,
      navigateTo: ({
        pageId,
        appState,
        referrer,
        relativeUrl,
        displayMode,
        history,
      }) => {
        navigateTo(
          {
            pageId,
            appState: appState || relativeUrl,
            referrer,
          },
          { displayMode, history },
        );
      },
      getHostContainer,
      showToast: showToastCompat(showToast),
      useAppLoaded: () => {
        useComponentLoaded();
      },
      onBeforeUnload,
      ...wixPatternsEssentialsOverridesProp,
    }),
  );

  const [wixPatternsEssentials] = useState(() =>
    buildWixPatternsEssentials(essentials, {
      overrides: wixPatternsEssentialsOverrides,
    }),
  );

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