import * as React from 'react'
import { connect } from 'react-redux'
import * as cx from 'classnames'
import { StylableComponent } from '../../theme'
import { ModalPopupProps, ModalPopupComponentProps } from '../interfaces'
import { hideModal } from '../actions'
import { Column } from '../../flex'
import { OpenableComponent } from '../../common'
import { MODAL_REDUCER_KEY } from '../constants'

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

class ModalPopupComponent extends OpenableComponent<ModalPopupComponentProps> {

    public renderCloseButton() {
        if (!this.props.closeButton) return null
        return (
            <a className={styles.close}
                onClick={this.props.closeModal}>
                    <span>{'\u00D7'}</span>
            </a>
        )
    }

    public render() {
        return (
            <div
                ref={this.setContainerRef}
                className={cx(styles.modalPopup, this.props.className)} >
                {this.renderCloseButton()}
                {this.props.children}
            </div>
        )
    }

    public isActive() {
        const { state, backgroundActive } = this.props
        return backgroundActive || (state.modalProps && state.modalProps.backgroundActive)
    }

    public handleClose() {
        this.props.closeModal()
    }

}

export class ModalPopupContent extends StylableComponent<any> {
    public render() {
        return (
            <div className={cx( styles.modalContent, this.props.className )}>
                {this.props.children}
            </div>
        )
    }
}

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

const mapDispatchToProps = {
    closeModal: hideModal,
}

export const ModalPopup = connect(mapStateToProps, mapDispatchToProps)(ModalPopupComponent)