import PropTypes from 'prop-types';
import React from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import { block } from 'bem-cn';

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

import Icon from 'ui/Icon';
import Unit from 'ui/Unit';

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

import './index.css';

const bSessionSelect = block('session-select');

const SessionSelect = React.createClass({

    mixins: [PureRenderMixin, StoreMixin],

    getStoreState() {
        const sessions = SessionStore.getAllMap();
        const { props, state } = this;

        const nextState = { sessions };

        if (!state || !state.sessionsOrder) {
            nextState.sessionsOrder = this._getSessionsOrder(sessions, props.authSessionId);
        }

        if (!state || !state.selectedSessionId) {
            nextState.selectedSessionId = props.selectedSessionId || props.authSessionId;
        }

        return nextState;
    },

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

    _getSessionsOrder(sessions, authSessionId) {
        const order = Object.keys(sessions);

        return [authSessionId, ...order.filter(sessionId => sessionId !== authSessionId)];
    },

    _renderSessions() {
        const { sessions, sessionsOrder } = this.state;

        return (
            <div className={bSessionSelect('sessions')}>
                {sessionsOrder.map(id => this._renderSession(sessions[id]))}
            </div>
        );
    },

    _renderSession(session) {
        const { selectedSessionId } = this.state;
        const sessionId = session.getId();
        const login = session.getLogin();

        return (
            <div
                className={bSessionSelect('session', { selected: sessionId === selectedSessionId })}
                key={`session-${sessionId}`}
                role="button"
                tabIndex="0"
                onClick={this._onSessionClick.bind(this, sessionId)}
            >
                <Unit.Avatar avatar={session.getAvatar()} />
                <div className={bSessionSelect('session-name')} title={login}>
                    {login}
                </div>
            </div>
        );
    },

    _onSessionClick(sessionId) {
        if (sessionId !== this.state.selectedSessionId) {
            this.setState({
                selectedSessionId: sessionId,
            });

            this.props.onSelect(sessionId);
        }
    },

    _onSessionAddClick() {
        Url.open(AuthStore.getNewSessionUrl(location.href));
    },

    render() {
        return (
            <div className={bSessionSelect}>
                {this._renderSessions()}
                <div
                    className={bSessionSelect('session', { add: true })}
                    role="button"
                    tabIndex="0"
                    onClick={this._onSessionAddClick}
                >
                    <Icon type="plus-solid-circle" size="xxl" />
                    <div className={bSessionSelect('session-name')}>
                        {i18n('registration.add_account')}
                    </div>
                </div>
            </div>
        );
    },
});

SessionSelect.propTypes = {
    selectedSessionId: PropTypes.string,
    authSessionId: PropTypes.string,
    onSelect: PropTypes.func,
};

export default SessionSelect;
