import React, { useState, useEffect } from 'react';
import cx from 'classnames';
import Modal from 'react-modal';
import { FullscreenModalContext } from './components/fullScreenModalContext';
import { CLASSNAME } from './constants';

export interface FullscreenModalProps {
    /** Actual content of the modal **/
    children: React.ReactNode;
    /** Additional class names to apply to the modal portal */
    className?: string;
    /** String indicating the layout of the modal. Defaults to undefined. */
    layout?: 'fluid';
    /** Boolean describing if the modal should be shown or not. Defaults to true. */
    isOpen?: boolean;
    /* Function that will be run when the modal is requested to be closed, prior to actually closing. */
    onRequestClose?: Modal.Props['onRequestClose'];
}

/**
 * FullScreenModal interrupt users to present a sub-process or experience connected to the object page.
 *
 * @type organism
 * @status live
 * @tags overlays
 */
export const FullscreenModal: React.FC<FullscreenModalProps> = ({
    children,
    className,
    layout,
    isOpen = true,
    onRequestClose,
}) => {
    // Monitor body margin-top to account for Intercom banners, which offset the page by a variable height
    const [marginTop, setMarginTop] = useState<string | undefined>(() => {
        return document.body.style.marginTop || undefined;
    });

    useEffect(() => {
        const observer = new MutationObserver((mutations) => {
            mutations.forEach((mutation) => {
                if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
                    setMarginTop(document.body.style.marginTop || undefined);
                }
            });
        });

        observer.observe(document.body, {
            attributes: true,
            attributeFilter: ['style'],
        });

        return () => {
            observer.disconnect();
        };
    }, []);

    return (
        <Modal
            isOpen={isOpen}
            className={'ReactModal'}
            appElement={document.getElementById('root') ?? []}
            portalClassName={cx('ReactModalPortal', `ReactModalPortal-${CLASSNAME}`, className)}
            style={{
                overlay: {
                    backgroundColor: 'revert-layer',
                    marginTop,
                    zIndex: 1000,
                },
            }}
            onRequestClose={onRequestClose}
        >
            <FullscreenModalContext.Provider value={{ isFSM: true }}>
                <div className={CLASSNAME}>
                    {layout === 'fluid' ? (
                        <div className={`${CLASSNAME}-fluid`} data-testid={`${CLASSNAME}-fluid`}>
                            {children}
                        </div>
                    ) : (
                        <>{children}</>
                    )}
                </div>
            </FullscreenModalContext.Provider>
        </Modal>
    );
};
