import React from 'react'
import PropTypes from 'prop-types'
import modals from 'containers/modals'
import Debug from 'common-fe/utils/debug'
import modalTypes from './modal-types'

class ModalManager extends React.PureComponent {
    static modalFor = (type) => modals[type] || null

    dismissModal = () => {
        const {
            modal: {onDismiss},
            hideModal,
        } = this.props
        hideModal && hideModal()
        onDismiss && onDismiss()

        return Promise.resolve()
    }

    render() {
        const {
            modal: {isShowing, type, ...customProps},
        } = this.props
        const modal = ModalManager.modalFor(type)

        if (!modal) {
            // DEFAULT is the default modal type initialized in the reducer and
            // is intentionally null.
            // We want to warn ourselves when the modal manager isn't able to
            // resolve a modal for the specified type in every other case.
            type !== modalTypes.DEFAULT &&
                Debug.warn(`WARN: No modal found for type ${type}.`)
            return null
        }

        const {template: Modal, templateProps, ...modalProps} = modal

        return (
            <Modal
                {...customProps}
                {...modalProps}
                isShowing={isShowing}
                templateProps={templateProps}
                onDismiss={this.dismissModal}
            />
        )
    }
}

ModalManager.propTypes = {
    modal: PropTypes.shape({
        isShowing: PropTypes.bool.isRequired,
        type: PropTypes.string.isRequired,
        template: PropTypes.func,
        templateProps: PropTypes.object,
        onDismiss: PropTypes.func,
    }).isRequired,
    hideModal: PropTypes.func,
}

export default ModalManager
