import React, {PropTypes} from 'react';
import BaseModal from 'react-bem-components/lib/Modal';

const ANIMATION_DURATION_PROPS = ['animationDuration', 'webkitAnimationDuration'];

function getAnimationDuration(style) {
    for (let i = 0, length = ANIMATION_DURATION_PROPS.length; i < length; i++) {
        let prop = ANIMATION_DURATION_PROPS[i];
        let duration = style[prop];

        if (duration) {
            let value = parseFloat(duration, 10);

            if (isNaN(value)) {
                break;
            }

            if (duration.substr(-2) !== 'ms') {
                value *= 1000;
            }

            return value;
        }
    }

    return 0;
}

var Modal = React.createClass({
    displayName: 'Modal',

    _handleCloseClick: function(event) {
        event.preventDefault();

        var { onCancel } = this.props;

        if (onCancel) {
            onCancel({ target: this.refs.modal.block });
        }

        this.refs.modal.close();
    },

    _handleModalOpen: function () {
        var {onOpen} = this.props;
        var block = this.refs.modal.block

        if (onOpen) {
            onOpen({
                target: block
            });
        }

        if (this._animationDuration != null) {
            clearTimeout(this._animationTimeout);
        } else {
            let style = getComputedStyle(block.domElem[0]);

            this._animationDuration = getAnimationDuration(style);
        }
    },

    _handleModalClose: function () {
        var {onClose, onBeforeClose} = this.props;

        var payload = {
            target: this.refs.modal.block
        };

        if (onBeforeClose) {
            onBeforeClose(payload);
        }

        this._animationTimeout = setTimeout(function() {
            onClose(payload);
        }, this._animationDuration);
    },

    render: function() {
        return (
            <BaseModal {...this.props} ref="modal"
                onClose={this._handleModalClose}
                onOpen={this._handleModalOpen}>
                <div className="modal__close" onClick={this._handleCloseClick} />
                <div className="modal__title">
                    {this.props.title}
                </div>
                <div className="modal__body">
                    {this.props.children}
                </div>
            </BaseModal>
        );
    }
});

Modal.propTypes = {
    title: PropTypes.string,
    onBeforeClose: PropTypes.func
};

export default Modal;
