import * as React from 'react';
import Modal from 'react-modal';
import { InitOptions, UI_LAYER } from '@usercentrics/cmp-browser-sdk';

import { UsercentricsProvider } from './contexts/UsercentricsContext/UsercentricsProvider';
import { Container, ContainerProps } from './Container';
import { AbTestValue, Appearance } from './contexts/UsercentricsContext/types';

export interface UsercentricsProps extends ContainerProps {
  appRootElementId: string;
  disabled?: boolean;
  settingsId: string;
  options?: InitOptions & { appearance?: Appearance; showCloseAndAcceptAllButton?: boolean };
  abTestValue?: AbTestValue;
  consentEventName?: string;
  activeLayer?: UI_LAYER;
  loadingUI?: () => JSX.Element;
}

export const Usercentrics = ({
  appRootElementId,
  disabled,
  settingsId,
  options,
  abTestValue,
  consentEventName,
  activeLayer,
  loadingUI = (): JSX.Element => <></>,
  ...rest
}: UsercentricsProps): JSX.Element => {
  React.useEffect(() => {
    Modal.setAppElement(`#${appRootElementId}`);
  }, [appRootElementId]);

  return (
    <UsercentricsProvider
      disabled={disabled}
      settingsId={settingsId}
      options={options}
      abTestValue={abTestValue}
      consentEventName={consentEventName}
      activeLayer={activeLayer}
      loadingUI={loadingUI}
    >
      <Container {...rest} />
    </UsercentricsProvider>
  );
};
