import * as React from 'react'
import { connect } from 'react-redux'
import { StylableComponent } from '../../theme'
import { ModalRootComponentProps } from '../interfaces'
import { Button } from '../../button'
import { ButtonBar } from '../../button-bar'
import { Icon } from '../../icon'
import { ModalPopup, ModalPopupContent } from './modal-popup'
import { hideModal } from '../actions'
import { MODAL_REDUCER_KEY } from '../constants'

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

interface ConfirmModalProps {
    icon?: string
    closeButton?: boolean
    onConfirm?: () => any
    onCancel?: () => any
}

interface ConfirmModalComponentProps extends ConfirmModalProps, ModalRootComponentProps { }

/**
 * A confirm modal takes optional handlers for its buttons
 * Any modal that uses this presentational component
 * must be independently registered with the ModalRoot
 */
class ConfirmModalComponent extends StylableComponent<ConfirmModalComponentProps> {

    public render() {
        const { icon, closeButton, children} = this.props
        return (
            <ModalPopup closeButton={closeButton}>
                <ModalPopupContent>
                    {icon
                        ? <Icon
                            className={styles.modalIcon}
                            size={32}
                            fill="primary"
                            icon={icon} />
                        : null}
                    <div className={styles.modalMessage}>{children}</div>
                </ModalPopupContent>
                <ButtonBar>
                    <Button onClick={this.onConfirm}>OK</Button>
                    <Button onClick={this.onCancel}>CANCEL</Button>
                </ButtonBar>
            </ModalPopup>
        )
    }

    private onConfirm = () => {
        const { closeModal, onConfirm } = this.props
        closeModal()
        if (onConfirm) onConfirm()
    }

    private onCancel = () => {
        const { closeModal, onCancel } = this.props
        closeModal()
        if (onCancel) onCancel()
    }
}

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

const mapDispatchToProps = {
    closeModal: hideModal,
}

export const ConfirmModal = connect(mapStateToProps, mapDispatchToProps)(ConfirmModalComponent)