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.monoorg.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 bRegistration = block('registration');

const Registration = React.createClass({

    mixins: [PureRenderMixin, StoreMixin],

    getStoreState() {
        const { selectedSessionId } = this.state || {};
        const authSessionId = AuthStore.getUserId();

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

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

        const authSessionId = AuthStore.getUserId();

        // TODO: переделать, когда научимся добавлять пользователей в несколько организаций [multi-org]
        const orgId = SessionStore.get(authSessionId).getFirstOrgId(); // Беру первую организацию, пока одна всегда

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

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

        if (loading) {
            return;
        }

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

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

        ['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);
            });
    },

    _onOrganizationCreated(response = {}) {
        const { selectedSessionId } = this.state;
        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)));

        if (selectedSessionId !== AuthStore.getUserId()) {
            redirectUrl = AuthStore.getSessionChangeUrl(selectedSessionId, redirectUrl);
        }

        Url.open(redirectUrl);
    },

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

    _onSelect(selectedSessionId) {
        this.setState({ selectedSessionId }, () => {
            window.location.href = AuthStore.getSessionChangeUrl(selectedSessionId, window.location.href);
        });
    },

    _onEnterClick(orgId) {
        const { selectedSessionId } = this.state;
        let redirectUrl = Url.getLocation(Url.getOrganizationPath(orgId, getRedirectUrl()));

        if (selectedSessionId !== AuthStore.getUserId()) {
            redirectUrl = AuthStore.getSessionChangeUrl(selectedSessionId, redirectUrl);
        }

        Url.open(redirectUrl);
    },

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

        if (!ready) {
            return null;
        }

        let controlsContent;

        // TODO: переделать, когда научимся добавлять пользователей в несколько организаций [multi-org]
        const orgId = SessionStore.get(selectedSessionId).getFirstOrgId(); // Беру первую организацию, пока одна всегда

        if (!orgId) {
            controlsContent = [
                <Button
                    key="1"
                    text={ConfigStore.get('ui.allowCreateYaOrg') ?
                        i18n('registration.add_connect_org') :
                        i18n('registration.create_organization')}
                    view="action"
                    type="submit"
                    width="available"
                    busy={loading}
                    onClick={this._createOrganization}
                />,
                <YaOrgButton key="2" />,
            ];
        } else {
            controlsContent = (
                <Button
                    text={i18n('registration.enter_organization')}
                    view="action"
                    type="submit"
                    width="available"
                    busy={loading}
                    onClick={this._onEnterClick.bind(this, orgId)}
                />
            );
        }

        return (
            <Form className={bRegistration}>
                <h1 className={bRegistration('header')}>
                    {orgId ? i18n('registration.header_org') : i18n('registration.header')}
                </h1>

                <SessionSelect
                    onSelect={this._onSelect}
                    selectedSessionId={selectedSessionId}
                    authSessionId={authSessionId}
                />

                <Form.Error value={error} mod="standalone" />
                <div className={bRegistration('controls')}>
                    {controlsContent}
                </div>
            </Form>
        );
    },
});

export default Registration;
