import React from 'react';
import { Button } from 'lego-on-react';
import block from 'bem-cn';
import AddDomainModal from 'components2/AddDomainModal';
import hasPermission from 'lib2/hasPermission';
import { i18n } from 'i18n2';

const b = block('add-domain-control');

export default class AddDomainControl extends React.PureComponent {
    constructor(props) {
        super(props);

        this.state = {
            modalOpen: props.defaultModalOpen,
        };

        this._onButtonClick = this._onButtonClick.bind(this);
        this._onCancel = this._onCancel.bind(this);
        this._onSubmit = this._onSubmit.bind(this);
    }

    _onButtonClick() {
        this.setState({
            modalOpen: true,
        });
    }

    _onSubmit(domain) {
        this.setState({
            modalOpen: false,
        });

        let { onSubmit } = this.props;

        if (onSubmit) {
            return onSubmit(domain);
        }
    }

    _onCancel() {
        this.setState({
            modalOpen: false,
        });
    }

    render() {
        let { cls, ...otherProps } = this.props;
        let { modalOpen } = this.state;

        if (!hasPermission('add_domains')) {
            return null;
        }

        return (
            <React.Fragment>
                <Button
                    cls={b({}).mix(cls)}
                    text={i18n('domain.action_description.add')}
                    onClick={this._onButtonClick}
                    {...otherProps}
                />
                <AddDomainModal
                    visible={modalOpen}
                    onCancel={this._onCancel}
                    onSubmit={this._onSubmit}
                />
            </React.Fragment>
        );
    }
}
