import React from 'react';
import { Button } from 'lego-on-react';
import StoreMixin from 'lib/StoreMixin';
import Url from 'lib/Url';
import { i18n } from 'lib/i18n';

import Header from 'components/Header';
import Unit from 'ui/Unit';

import ConfigStore from 'stores/Config';
import AuthStore from 'stores/Auth';
import GroupStore from 'stores/Groups';
import UserStore from 'stores/Users';
import OrganizationStore from 'stores/Organizations';

import ModalBox from 'components/ModalBox';

import './index.css';

const Forbidden = React.createClass({

    mixins: [StoreMixin],

    getStoreState() {
        return {
            currentUser: AuthStore.getUser(),
            admin: this._getRandomAdmin(),
        };
    },

    componentDidMount() {
        this.subscribe([AuthStore, GroupStore, UserStore, OrganizationStore]);
    },

    _getRandomAdmin() {
        const adminGroup = GroupStore.getAdminGroup();

        if (!adminGroup) {
            return null;
        }

        if (this._admin) {
            return this._admin;
        }

        const adminList = adminGroup.getMembers();
        const admin = adminList[Math.floor(Math.random() * adminList.length)];

        if (!admin) {
            return null;
        }

        this._admin = admin.getNickname();

        return this._admin;
    },

    _changeUser() {
        location.href = Url.build(ConfigStore.get('passport.session.login'), {
            retpath: Url.getReturnPath() || Url.getLocation('/'),
        });
    },

    _toSettings() {
        location.href = Url.getLocation(Url.getPath('admin', 'subscription', 'services'));
    },

    _getImageIndex() {
        return Math.floor(1 + 3 * Math.random());
    },

    _renderCurrentUser(user) {
        if (!user || !user.getId()) {
            return null;
        }

        const name = user.getShortFullName() || AuthStore.getDisplayName();
        const description = `${user.getNickname()}@`;

        return (
            <div className="forbidden-page__user">
                <Unit
                    avatar={user.getAvatar()}
                    size="l"
                    title={name}
                    description={description}
                    container={false}
                />
            </div>
        );
    },

    _getContent(type, options) {
        let noDescription = !AuthStore.getUserId() || options.reason === 'cannot_use_connect';

        if (type === 'description' && noDescription) {
            return null;
        }

        const forAdmin = AuthStore.isAdmin();
        const noAdmin = !options.params || !options.params.admin;
        const multiOrg = OrganizationStore.getSize() > 1;

        const keys = [
            forAdmin && `${options.source}.${options.reason}.for_admin`,
            noAdmin && `${options.source}.${options.reason}.no_admin`,
            multiOrg && `${options.source}.${options.reason}.multiorg`,
            `${options.source}.${options.reason}.regular`,
            `${options.source}.${options.reason}`,
            forAdmin && `common.${options.reason}.for_admin`,
            noAdmin && `common.${options.reason}.no_admin`,
            multiOrg && `common.${options.reason}.multiorg`,
            `common.${options.reason}.regular`,
            `common.${options.reason}`,
        ].filter(Boolean);

        return keys.map(key => i18n(`forbidden_page.${type}.${key}`, options.params))
            .filter(item => item && (typeof item === 'string'))[0];
    },

    _renderActions({ source }) {
        const actions = [];

        if (!AuthStore.getUserId()) {
            actions.push(
                <Button
                    key="login"
                    text={i18n('common.action.login')}
                    onClick={this._changeUser}
                    theme="action"
                    size="l"
                />
            );
        } else if (AuthStore.isAdmin() && source !== 'connect') {
            actions.push(
                <Button
                    key="toSettings"
                    text={i18n('forbidden_page.action.go_to_settings')}
                    onClick={this._toSettings}
                    theme="action"
                    size="l"
                />
            );
        } else {
            // Todo: добавить кнопку отправки,
            // когда будет готова отправка сообщения админу сервиса
            actions.push(
                <Button
                    key="changeUser"
                    text={i18n('forbidden_page.action.login')}
                    onClick={this._changeUser}
                    theme="action"
                    size="l"
                />
            );
        }

        return (
            <div className="forbidden-page__actions">
                {actions}
            </div>
        );
    },

    render() {
        const { source, reason } = this.props;
        const { currentUser, admin } = this.state;

        const retpath = Url.getReturnPath() || Url.getLocation('/');

        const contentOptions = {
            reason: reason || 'unknown',
            source: source || 'connect',
            params: {
                admin,
                user_approval_url: ConfigStore.get('passport.session.approveUser', {
                    retpath: encodeURIComponent(retpath),
                }),
                troubleshooting_url: ConfigStore.get('ui.help.feedback'),
            },
        };

        const content = {
            header: this._getContent('header', contentOptions),
            description: this._getContent('description', contentOptions),
        };

        return (
            <div className="forbidden-page">
                <Header searchEnabled={false} />
                <div className={`forbidden-page__content forbidden-page__${contentOptions.source}`}>
                    <div className="forbidden-page__details">
                        <div className="forbidden-page__service-icon" />
                        <h1 className="forbidden-page__header">
                            {content.header}
                        </h1>
                        {this._renderCurrentUser(currentUser)}
                        {content.description && (
                            <div
                                className="forbidden-page__description"
                                dangerouslySetInnerHTML={{ __html: content.description }}
                            />
                        )}
                        {this._renderActions(contentOptions)}
                    </div>
                    <div className={`forbidden-page__image forbidden-page__image-${this._getImageIndex()}`} />
                </div>
                <ModalBox />
            </div>
        );
    },

});

export default Forbidden;
