import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import { CSSTransition, SwitchTransition } from 'react-transition-group';

import ModalContents from './atoms/modal-contents/ModalContents';
import { createNamespace } from '../../tools/namingTools';
import './styles/Modal.scss';

const n = createNamespace('Modal');

// for global modals, i.e. not rendered as child of another element, we render in a portal
// and there could exist only one modal at a time
let portalDomNode;

const animTime = 200; // ms
const ModalComponent = ({
    currentKey,
    currentItem,
    onClose,
    isGlobal,
    left,
    top
}) => {
    const wrapperProps = n('transition').withVariables({ animTime: `${animTime}ms` }).props;

    if (isGlobal) {
        if (!portalDomNode) {
            portalDomNode = document.createElement('div');
            portalDomNode.classList.add(n('portal').props.className);
            document.body.append(portalDomNode);
        }
    }
    const content = (
        <SwitchTransition>
            <CSSTransition
                key={currentKey}
                {...wrapperProps}
                appear
                in
                timeout={currentItem ? animTime : 0}
                classNames={wrapperProps.className}
            >
                <div>
                    {currentItem && (
                        <ModalContents onClose={onClose} left={left} top={top} animTime={animTime}>
                            {currentItem}
                        </ModalContents>
                    )}
                </div>
            </CSSTransition>
        </SwitchTransition>
    );

    // on desktop, element is placed normally in the flow
    if (!isGlobal) {
        return content;
    }

    return ReactDOM.createPortal(
        content,
        portalDomNode
    );
};

ModalComponent.propTypes = {
    currentKey: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
    currentItem: PropTypes.node,
    isGlobal: PropTypes.bool,
    onClose: PropTypes.func,
    left: PropTypes.number,
    top: PropTypes.number
};

ModalComponent.defaultProps = {
    onClose: () => null,
    currentItem: null,
    isGlobal: true,
    left: 0,
    top: 0
};

export default ModalComponent;
