import React from 'react'
import PropTypes from 'prop-types'
import toasts from 'containers/toasts'
import Debug from 'common-fe/utils/debug'
import toastTypes from './toast-types'

class ToastManager extends React.PureComponent {
    static toastFor = (type) => toasts[type]

    timeout = null

    componentDidUpdate() {
        const {
            toast: {duration, isShowing},
        } = this.props

        if (isShowing && duration) {
            this.timeout = setTimeout(this.hideToast, duration)
        }
    }

    componentWillUnmount() {
        clearTimeout(this.timeout)
        this.hideToast()
    }

    hideToast = () => {
        const {
            toast: {isShowing},
            hideToast,
        } = this.props
        isShowing && hideToast && hideToast()
    }

    render() {
        const {
            toast: {duration, type, ...toastProps},
            hideToast,
        } = this.props
        const toast = ToastManager.toastFor(type)

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

        const {template: Toast, ...additionalProps} = toast

        return (
            <Toast {...toastProps} {...additionalProps} onDismiss={hideToast} />
        )
    }
}

ToastManager.propTypes = {
    toast: PropTypes.shape({
        duration: PropTypes.number.isRequired,
        isShowing: PropTypes.bool.isRequired,
        type: PropTypes.string.isRequired,
        template: PropTypes.string,
    }).isRequired,
    hideToast: PropTypes.func,
}

export default ToastManager
