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

import { DetailsModal, DetailsModalProps } from './components/DetailsModal/DetailsModal';
import { UsercentricsProvider } from './contexts/UsercentricsContext';
import { AbTestValue, Appearance } from './contexts/UsercentricsContext/types';

export interface UsercentricsDetailsProps extends DetailsModalProps {
  appRootElementId: string;
  disabled?: boolean;
  settingsId: string;
  options?: InitOptions & { appearance?: Appearance; showCloseAndAcceptAllButton?: boolean };
  abTestValue?: AbTestValue;
  consentEventName?: string;
  loadingUI?: () => JSX.Element;
  onConsentStatusUpdate: (details: Record<string, string>) => void;
}

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

  const handleConsentUpdate = React.useCallback(
    (event: CustomEvent) => {
      if (event.detail && event.detail.event === 'consent_status') {
        onConsentStatusUpdate(event.detail);
      }
    },
    [onConsentStatusUpdate]
  );

  React.useEffect(() => {
    window.addEventListener(consentEventName as any, handleConsentUpdate);
    return () => {
      window.removeEventListener(consentEventName as any, handleConsentUpdate);
    };
  }, [consentEventName, onConsentStatusUpdate, handleConsentUpdate]);

  return (
    <UsercentricsProvider
      disabled={disabled}
      settingsId={settingsId}
      options={options}
      abTestValue={abTestValue}
      consentEventName={consentEventName}
      loadingUI={loadingUI}
    >
      <DetailsModal showBackButton={false} {...rest} />
    </UsercentricsProvider>
  );
};
