import _ from 'lodash';
import React from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';

import { block } from 'bem-cn';
import Form from 'ui/Form';
import Button from 'lego-ui/Button';
import SessionSelect from 'components/SessionSelect';

import OrganizationActions from 'actions/OrgSetup';

import AuthStore from 'stores/Auth';
import ConfigStore from 'stores/Config';
import SessionStore from 'stores/Sessions';

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

import { YaOrgButton } from './YaOrgButton';
import './index.multiorg.css';

const SourcePresetMap = {
    tracker_promo: 'tracker',
};

function getPreset() {
    return Url.getQueryParam('preset') || SourcePresetMap[Url.getQueryParam('source')];
}

function getRedirectUrl(isNewOrg) {
    let redirectUrl = Url.getQueryParam('retpath');

    if (redirectUrl) {
        return decodeURIComponent(redirectUrl);
    }

    return isNewOrg ? Url.getOnboargingUrl() : Url.getDashboardUrl();
}

const b = block('registration');

const Registration = React.createClass({

    mixins: [PureRenderMixin, StoreMixin],

    getStoreState() {
        const authSessionId = AuthStore.getUserId();

        return {
            preset: getPreset(),
            source: Url.getSourceParams('y4b'),
            authSessionId,
        };
    },

    componentDidMount() {
        this.subscribe([SessionStore, AuthStore]);

        // ?session=current - редирект в первую организацию текущего аккаунта
        let orgId = SessionStore.get(AuthStore.getUserId()).getFirstOrgId();

        if (orgId && Url.getQueryParam('session') === 'current') {
            location.href = Url.getOrganizationPath(orgId, getRedirectUrl());
        } else {
            this.setState({ ready: true });
        }
    },

    _createOrganization() {
        const { loading, authSessionId } = this.state;

        if (loading) {
            return;
        }

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

        const data = {
            language: AuthStore.getLocale(),
            tld: ConfigStore.get('app.tld'),
            uid: authSessionId,
        };

        ['source', 'preset'].forEach(field => {
            const fieldFromQuery = this.state[field];

            if (fieldFromQuery) {
                data[field] = fieldFromQuery;
            }
        });

        OrganizationActions.createWithExternalUser(data)
            .then(response => {
                if (response.errors) {
                    const errorData = response.errors.toJS();

                    return this._showError(errorData._common[0]);
                }

                this._onOrganizationCreated(response);
            })
            .catch(err => {
                let backendKey = '';
                const unknownKey = 'common.error.unknown';

                if (err && err.code) {
                    backendKey = `backend_errors.${err.code}`;
                }

                const errMsg = i18n(backendKey || unknownKey) || i18n(unknownKey);

                this._showError(errMsg);
            });
    },

    _cancel() {
        window.location.href = Url.getReturnPath() || '/portal/home';
    },

    _onOrganizationCreated(response = {}) {
        const { orgId } = response;
        const source = (Url.getQueryParam('source') || 'Registration')
            .split('_')
            .map(_.capitalize)
            .join('');

        Metrika.reachGoal(`OrganizationCreatedFrom${source}`);

        let redirectUrl = Url.getLocation(Url.getOrganizationPath(orgId, getRedirectUrl(true)));

        Url.open(redirectUrl);
    },

    _showError(error) {
        this.setState({
            error,
            loading: false,
        });
    },

    _onSelect(sessionId) {
        Url.open(AuthStore.getSessionChangeUrl(sessionId, window.location.href));
    },

    render() {
        const { error, loading, ready, authSessionId } = this.state;

        if (!ready) {
            return null;
        }

        return (
            <Form className={b}>
                <h1
                    className={b('header')}
                    dangerouslySetInnerHTML={{
                        __html: i18n('registration.header_multiorg'),
                    }}
                />
                <SessionSelect
                    onSelect={this._onSelect}
                    authSessionId={authSessionId}
                />
                <Form.Error value={error} mod="standalone" />
                <div className={b('controls')}>
                    <Button
                        text={ConfigStore.get('ui.allowCreateYaOrg') ?
                            i18n('registration.add_connect_org') :
                            i18n('registration.add_org')}
                        view="action"
                        type="submit"
                        width="available"
                        busy={loading}
                        onClick={this._createOrganization}
                    />
                    <YaOrgButton />
                    {Boolean(AuthStore.getSession().get('org_id')) && (
                        <Button
                            text={i18n('common.action.cancel')}
                            view="normal"
                            width="available"
                            onClick={this._cancel}
                        />
                    )}
                </div>
            </Form>
        );
    },
});

export default Registration;
