import {
  CairoProvider as CairoProviderCore,
  CairoProviderProps as CairoProviderCoreProps,
} from '@wix/bex-core/react';
import { configure } from '@wix/bex-utils/react-dom';
import React, { useState } from 'react';
import { version as cairoVersion } from '../version';

import '../styles.global.css';

import * as wixDesignSystemVersion from '../wix-design-system-version';
import { minimalRequiredWdsRuntimeCheck } from '../minimalRequiredWdsRuntimeCheck';
import { PatternsThemeProvider } from '../themes/PatternsThemeProvider';
import { panelTheme } from '../themes/panel-theme';

configure();

if (process.env.NODE_ENV !== 'production') {
  minimalRequiredWdsRuntimeCheck({
    required: wixDesignSystemVersion.required,
  });
}

export interface CairoProviderProps extends CairoProviderCoreProps {}

export function CairoProvider(props: CairoProviderProps) {
  const { value: valueProp, children, layoutType, ...rest } = props;

  const [value] = useState(() => ({
    ...valueProp,
    environment: {
      ...valueProp.environment,
      uiLibVersion: cairoVersion,
    },
  }));

  let child = children;

  if (layoutType === 'panel') {
    child = (
      <PatternsThemeProvider value={panelTheme}>
        {children}
      </PatternsThemeProvider>
    );
  }
  return (
    <CairoProviderCore {...rest} value={value} layoutType={layoutType}>
      {child}
    </CairoProviderCore>
  );
}
