import _ from 'lodash';
import React from 'react';
import FormMixin from 'lib/FormMixin';

import ConfigStore from 'stores/Config';
import OrgSetupActions from 'actions/OrgSetup';

import Metrika from 'lib/metrika';
import { i18n } from 'lib/i18n';
import Url from 'lib/Url';
import getErrors from 'lib/getErrors';

import Form from 'lego-ui/Form';
import Input from 'lego-ui/Input';
import Button from 'lego-ui/Button';

const AddOrgForm = React.createClass({

    mixins: [FormMixin],

    getInitialState() {
        return {
            domainName: '',
        };
    },

    _reset() {
        if (this.state.error) {
            this.setState({ error: null });
        }
    },

    _handleDomainNameInput(event) {
        this.setState({
            domainName: event.target.value,
        });
    },

    _filterInput(data) {
        data.domain_name = data.domain_name
            .replace(/^(https?:)?\/\//, '')
            .replace(/\/$/, '');

        return data;
    },

    _handleFormSubmit(data) {
        this._filterInput(data);
        this._reset();
        this.setState({ busy: true });

        if (!data.domain_name) {
            this.setState({
                error: i18n('backend_errors.domains.domain_prohibited'),
                busy: false,
            });

            return;
        }

        return OrgSetupActions.addDomain({
            ...data,
            source: Url.getSourceParams('org_switch'),
        })
            .then(response => {
                const errors = getErrors(response, ['domains']);

                this.setState({ busy: false });

                if (errors.get('_common')) {
                    this.setState({ error: errors.get('_common') });

                    return;
                }

                const orgId = _.get(response, 'added_organization.org_id');

                if (orgId) {
                    Metrika.reachGoal('OrganizationCreatedFromHeader');

                    location.href = Url.getOrganizationPath(orgId, Url.getPath('services', 'webmaster'));
                }
            })
            .catch(() => {
                this.setState({ busy: false });
            });
    },

    render() {
        const { error } = this.state;

        return (
            <Form
                className="add-org-form form"
                onSubmit={this._handleFormSubmit}
            >

                <input type="hidden" name="tld" value={ConfigStore.get('app.tld')} />

                <Form.Item>
                    <Form.Label>
                        <span
                            dangerouslySetInnerHTML={{
                                __html: i18n('organization_setup.new_org.tip'),
                            }}
                        />
                    </Form.Label>
                    <Input
                        name="domain_name"
                        width="available"
                        autoFocus
                        value={this.state.domainName}
                        onKeyDown={this._reset}
                        onInput={this._handleDomainNameInput}
                    />
                </Form.Item>

                <div className="add-org-form__error">
                    {error}
                </div>

                <div className="add-org-form__actions">
                    <Button
                        text={i18n('organization_setup.new_org.add')}
                        type="submit"
                        busy={this.state.busy}
                        disabled={!this.state.domainName.trim()}
                        view="action"
                    />
                </div>

            </Form>
        );
    },

});

export default AddOrgForm;
