import PropTypes from 'prop-types';
import React from 'react';
import { Button } from 'lego-on-react';
import ModalActions from 'actions/Modal';
import { i18n } from 'lib/i18n';
import Form from 'ui/Form';

import './index.css';

const Confirm = React.createClass({

    componentDidMount() {
        const { confirmButton } = this.refs;

        if (confirmButton) {
            confirmButton.control.focus();
        }
    },

    _handleConfirm() {
        const { onConfirm } = this.props;

        ModalActions.close();

        if (onConfirm) {
            onConfirm();
        }
    },

    _handleReject() {
        const { onReject } = this.props;

        ModalActions.close();

        if (onReject) {
            onReject();
        }
    },

    _renderMessage() {
        const { message } = this.props;
        const props = {};

        if (typeof message === 'string') {
            props.dangerouslySetInnerHTML = { __html: message };
        } else if (message) {
            props.children = message;
        }

        return <div className="dialog-form__message" {...props} />;
    },

    render() {
        const { confirmButtonText, rejectButtonText, confirmButtonType, className, mod } = this.props;
        const classes = [
            'confirm-dialog-form',
            `confirm-dialog-form_${mod}`,
            'dialog-form',
            'form',
            className,
        ].join(' ');

        return (
            <Form
                className={classes}
                ref="form"
                onSubmit={this._handleConfirm}
                autoComplete={false}
            >
                {this._renderMessage()}
                <Form.Buttons mod="right-aligned">
                    <Button
                        text={rejectButtonText}
                        size="m"
                        theme="normal"
                        onClick={this._handleReject}
                    />
                    <Button
                        text={confirmButtonText}
                        ref="confirmButton"
                        size="m"
                        theme={confirmButtonType}
                        type="submit"
                    />
                </Form.Buttons>
            </Form>
        );
    },

});

Confirm.propTypes = {
    message: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
    mod: PropTypes.oneOf(['normal', 'warning']),
    onConfirm: PropTypes.func,
    onReject: PropTypes.func,
    className: PropTypes.string,
    confirmButtonText: PropTypes.string,
    rejectButtonText: PropTypes.string,
    confirmButtonType: PropTypes.string,
};

Confirm.defaultProps = {
    mod: 'normal',
    confirmButtonText: i18n('common.action.ok'),
    rejectButtonText: i18n('common.action.cancel'),
    confirmButtonType: 'action',
};

export default Confirm;
