import React from 'react';
import { TextInput } from 'lego-on-react';
import Modal from 'components2/Modal';
import InlineError from 'components2/InlineError';
import { ConfigStore } from 'lib2/stores';
import directory from 'api2/directory';
import metrika from 'api2/metrika';
import getSourceParam from 'lib2/getSourceParam';
import getOrgChangeUrl from 'lib2/getOrgChangeUrl';
import { i18n } from 'i18n2';
import bOrgSwitch from './block';

function stripDomain(s) {
    return s.replace(/^((https?:)?\/\/)?([^\/]+)(\/.*)?$/, '$3');
}

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

        this.state = {
            name: props.name || '',
        };

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

    _onChange(name) {
        this.setState({ name });
    }

    _onSubmit() {
        this.setState({
            busy: true,
            error: null,
        });

        metrika.send(
            'Новая организация с доменом',
            'Подключить',
            window.location.pathname
        );

        directory.send('POST', '/v11/organization/with-domain/', {
            body: JSON.stringify({
                domain_name: stripDomain(this.state.name),
                tld: ConfigStore.get('app.tld'),
                language: ConfigStore.get('app.locale'),
                source: getSourceParam('org_switch'),
            }),
        })
            .then(({ ok, status, body }) => {
                if (!ok) {
                    metrika.send(
                        'Новая организация с доменом',
                        'Ошибка при добавлении организации',
                        body.code,
                        window.location.pathname
                    );

                    return this.setState({
                        error: i18n(`backend_errors.domains.${body.code}`) ||
                            i18n(`backend_errors.${body.code}`) ||
                            i18n('common.error.generic', { code: status }),
                    });
                }

                let orgId = body && body.org_id;

                metrika.reachGoal('OrganizationCreatedFromHeader', [
                    'Новая организация с доменом',
                    'Организация создана',
                    orgId ? 'С редиректом в организацию' : 'Без редиректа в организацию',
                    window.location.pathname,
                ]);

                if (orgId) {
                    window.location.href = getOrgChangeUrl(orgId, '/portal/services/webmaster');
                }
            })
            .finally(() => {
                this.setState({
                    busy: false,
                });
            });
    }

    _onCancel() {
        let { onCancel } = this.props;

        if (onCancel) {
            onCancel();
        }

        metrika.send(
            'Новая организация с доменом',
            'Отменить/Закрыть',
            window.location.pathname
        );
    }

    render() {
        let { name, busy, error } = this.state;

        return (
            <Modal
                cls={bOrgSwitch('add-org-modal')}
                visible={this.props.visible}
            >
                <Modal.Title>
                    {i18n('organization_setup.new_org.title')}
                </Modal.Title>
                <Modal.CloseButton onClick={this._onCancel} />
                <Modal.Body>
                    <div
                        className={bOrgSwitch('add-org-tip')}
                        dangerouslySetInnerHTML={{
                            __html: i18n('organization_setup.new_org.tip'),
                        }}
                    />
                    <div className={bOrgSwitch('add-org-name')}>
                        <TextInput
                            theme="normal"
                            size="m"
                            cls={bOrgSwitch('add-org-input')}
                            text={name}
                            autoComplete={false}
                            onChange={this._onChange}
                        />
                    </div>
                    {error &&
                    <InlineError cls={bOrgSwitch('add-org-error')}>
                        {error}
                    </InlineError>}
                </Modal.Body>
                <Modal.ConfirmActions
                    onConfirm={this._onSubmit}
                    onCancel={this._onCancel}
                    confirmCaption={i18n('organization_setup.new_org.add')}
                    confirmDisabled={!name.trim() || busy}
                />
                <Modal.Busy visible={busy} />
            </Modal>
        );
    }
}
