import React from 'react';
import block from 'bem-cn';
import escape from 'lodash/escape';
import get from 'lodash/get';
import { TextInput } from 'lego-on-react';
import { i18n } from 'i18n2';

import directory from 'api2/directory';
import metrika from 'api2/metrika';

import notify from 'lib2/notify';
import getOrganization from 'lib2/getOrganization';
import getHelpUrl from 'lib2/getHelpUrl';

import { SessionStore, ConfigStore } from 'lib2/stores';

import Modal from 'components2/Modal';
import Form from 'components2/Form';
import InlineError from 'components2/InlineError';

import './index.css';

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

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

        this.state = {
            domain: '',
            busy: false,
            text: '',
        };

        this._onSubmit = this._onSubmit.bind(this);
        this._onCancel = this._onCancel.bind(this);
        this._onInputChange = this._onInputChange.bind(this);
        this._initInput = this._initInput.bind(this);
    }

    componentWillUnmount() {
        this._unmounted = true;
    }

    _onCancel() {
        this.props.onCancel();
        this._reset();
    }

    _reset() {
        this.setState({
            text: '',
            error: '',
        });
    }

    _onInputChange(text) {
        this.setState({ text });
    }

    _onSubmit() {
        const { onSubmit } = this.props;

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

        metrika.send(
            'Страница сервиса', 'webmaster',
            'Форма добавления алиаса', 'Добавить'
        );

        directory
            .send('POST', '/v11/domains/', {
                body: JSON.stringify({
                    name: this.state.text,
                }),
            })
            .then(({ ok, status, body }) => {
                if (!ok) {
                    return this.setState({
                        error: i18n(`backend_errors.domains.${body.code}`) || i18n(`backend_errors.${body.code}`) ||
                            i18n('common.error.generic', { code: status }),
                    });
                }

                notify(i18n('domain.status.added'));

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

    _initInput(input) {
        return input && input.focus();
    }

    render() {
        const { visible, cls } = this.props;
        const { busy, text, error } = this.state;

        const user = SessionStore.get('user');

        const domain = text ||
            get(getOrganization(), ['domains', 'master']) ||
            i18n('domain.new_alias.default_domain', { tld: ConfigStore.get('app.tld') });

        return (
            <Modal
                cls={b({}).mix(cls)}
                visible={visible}
            >
                <Modal.Title>
                    {i18n('domain.new_alias.title')}
                </Modal.Title>
                <Modal.CloseButton onClick={this._onCancel} />
                <Modal.Body>
                    <div
                        className={b('description')}
                        dangerouslySetInnerHTML={{
                            __html: i18n('domain.new_alias.description', {
                                help_url: getHelpUrl('ui.help.domains'),
                            }),
                        }}
                    />
                    <Form cls={b('form')}>
                        <TextInput
                            theme="normal"
                            size="m"
                            cls={b('input')}
                            name="domain-name"
                            text={text}
                            autocomplete={false}
                            onChange={this._onInputChange}
                            ref={visible && this._initInput}
                            focused
                        />
                        <div
                            className={b('hint')}
                            dangerouslySetInnerHTML={{
                                __html: i18n('domain.new_alias.tip', {
                                    email: escape(`${user.nickname || user.login}@${domain}`),
                                }),
                            }}
                        />
                        {error && (
                            <InlineError cls={b('error')}>
                                {error}
                            </InlineError>
                        )}
                        <Form.Actions
                            cls={b('actions')}
                            onSubmit={this._onSubmit}
                            onCancel={this._onCancel}
                            submitCaption={i18n('common.action.add')}
                            submitDisabled={!text}
                        />
                    </Form>
                </Modal.Body>
                <Modal.Busy visible={busy} />
            </Modal>
        );
    }
}
