import React, { ReactNode, useState } from 'react';
import {
  ContextType,
  WixPatternsEssentialsOverrides,
  showToastCompat,
} from '@wix/bex-core';
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';
import { usePageLocation } from '@wix/bex-core/react';

export interface WixPatternsGizaProviderProps {
  children?: ReactNode;
  value?: Partial<WixPatternsEssentialsOverrides>;
  localCache?: boolean;
  contextType?: ContextType;
}

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,
    localCache,
    contextType = 'ACCOUNT',
  } = props;
  const { showToast, navigateTo, onBeforeUnload, getHostContainer } =
    usePlatformApi();

  const essentials = useEssentials();

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

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

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