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

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

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

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

class _ModalRoot extends StylableComponent<ModalRootComponentProps> {
    private container: Element

    public constructor(props: ModalRootComponentProps, state: any) {
        super(props, state)
    }

    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)
