import * as React from 'react'
import { connect } from 'react-redux'
import { hideModal } from '../../actions/modal'
import { ModalRootProps, ModalRootComponentProps } from '../../interfaces/modal'
import { MODAL_REDUCER_KEY } from '../../reducers'
import { BASIC_MODAL_KEY, MESSAGE_MODAL_KEY } from '../../constants/modal'
import { BasicModal, MessageModal } from '.'

const styles = require('../../../src/styles/components/modal.scss')

const MODAL_COMPONENTS: { [id: string]: any } = {}

export const registerModalComponent = (id: string, component: any): void => {
    MODAL_COMPONENTS[id] = component
}

class _ModalRoot extends React.Component<ModalRootComponentProps, any> {
    private container: Element

    public constructor(props: ModalRootComponentProps) {
        super(props)
    }

    public componentDidMount() {
        document.addEventListener('keydown', this.handleKeyDown)
    }

    public componentWillUnmount() {
        document.removeEventListener('keydown', this.handleKeyDown)
    }

    public render() {
        const state = this.props.state
        const modalProps = state.modalProps || {}

        if (!state || state.modalType === '') return null

        const SpecificModal = MODAL_COMPONENTS[state.modalType]
        console.log('RENDERING SPECIFIC MODAL', MODAL_COMPONENTS, state.modalType,  SpecificModal)
        if (!SpecificModal) return null

        return (
            <div className={styles.modalContainer}>
                <SpecificModal {...this.props} />
            </div>
        )
    }

    private handleKeyDown = ({ code }: KeyboardEvent) => {
        if (code.toLowerCase() === 'escape') {
            this.props.closeModal()
        }
    }
}

const mapStateToProps = (state: any, ownProps: ModalRootProps) => ({
    state: state[MODAL_REDUCER_KEY],
})

const mapActionsToProps = {
    closeModal: hideModal,
}

export const ModalRoot = connect(mapStateToProps, mapActionsToProps)(_ModalRoot)
