import React from 'react';
import { Link, Icon } from 'lego-on-react';
import block from 'bem-cn';
import CrownOutlineIcon from 'components/Icon/CrownOutline';
import hasPermission from 'lib2/hasPermission';
import notify from 'lib2/notify';
import directory from 'api2/directory';
import metrika from 'api2/metrika';
import { i18n } from 'i18n2';
import './index.css';

const b = block('set-master-domain-control');

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

        this.state = {};

        this._setMaster = this._setMaster.bind(this);
    }

    _setMaster() {
        let { domain, onSubmit, trackId } = this.props;

        metrika.send(
            'Сделать домен основным',
            'Клик',
            trackId
        );

        this.setState({ busy: true });

        directory
            .send('PATCH', '/v11/organization/', {
                body: JSON.stringify({
                    master_domain: domain.name,
                }),
            })
            .then(({ ok }) => {
                metrika.send(
                    'Сделать домен основным',
                    ok ? 'Успешно' : 'Ошибка',
                    trackId
                );

                if (ok) {
                    notify(i18n('main_domain.status.changed'), 'success');
                } else {
                    notify(i18n('main_domain.status.failed_to_change'), 'error');
                }

                if (onSubmit) {
                    return onSubmit();
                }
            })
            .finally(() => {
                if (!this._unmounted) {
                    this.setState({ busy: false });
                }
            });
    }

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

        if (domain.master || !domain.owned || !hasPermission('change_master_domain')) {
            return null;
        }

        return (
            <Link
                cls={b({ busy }).mix(cls)}
                theme="normal"
                pseudo
                text={i18n('domain.action.set_as_main')}
                iconLeft={(
                    <Icon
                        cls={b('icon')}
                        glyph="yes"
                    >
                        <CrownOutlineIcon />
                    </Icon>
                )}
                {...otherProps}
                disabled={busy}
                onClick={this._setMaster}
            />
        );
    }
}
