import React from 'react';
import buildUrl from '@connect/url-placeholders';
import { getCookie } from '@connect/cookies-lite';
import MenuItem from './MenuItem';
import User from './User';
import { block } from 'bem-cn';

const bList = block('multi-session-list');

const Defaults = {
    passportHost: 'passport.yandex.ru',
    addAccountCaption: 'Add account'
};

const Passport = {
    addAccount: 'https://${passportHost}/auth?mode=add-user&retpath=${passportRetpath}',
    changeAccount: 'https://${passportHost}/passport?mode=embeddedauth&action=change_default&uid=${uid}&yu=${yu}&retpath=${passportRetpath}' // eslint-disable-line
};

export default ({
    cls,
    accounts,
    passportHost = Defaults.passportHost,
    passportRetpath = window.location.href,
    addAccount = true,
    addAccountCaption = Defaults.addAccountCaption,
    avatarUrl
}) => {
    let yu = getCookie('yandexuid');

    return (
        <div className={bList({}).mix(cls)}>
            {accounts.map(({ id: uid, name, login, avatar_id: avatarId }, index) => {
                let url = buildUrl(Passport.changeAccount, {
                    passportHost,
                    passportRetpath,
                    uid,
                    yu
                });

                return (
                    <MenuItem
                        cls={bList('item')}
                        url={url}
                        key={index}
                    >
                        <User
                            cls={bList('user')}
                            uid={uid}
                            name={name || login}
                            avatarId={avatarId}
                            avatarUrl={avatarUrl}
                        />
                    </MenuItem>
                );
            })}
            {addAccount &&
            <MenuItem
                cls={bList('item', { type: 'add-user' })}
                url={buildUrl(Passport.addAccount, { passportHost, passportRetpath })}
            >
                {addAccountCaption}
            </MenuItem>}
        </div>
    );
};
