import React from 'react';
import PropTypes from 'prop-types';
import { block } from 'bem-cn';
import { Service } from 'lib/services';
import Metrika from 'lib/metrika';
import { i18n } from 'lib/i18n';

import Url from 'lib/Url';

import { ServiceIcon } from 'components/Icon';

import Sidebar2 from 'components/Sidebar2';

import SERVICE_ITEMS from 'components/Dashboard/serviceList';
const bServiceSidebar = block('service-sidebar');

function isActive(item) {
    const url = typeof item.settingsLink === 'function' ? item.settingsLink() : item.settingsLink;
    const currentPath = location.href.replace(`${location.protocol}//${location.host}`, '');

    return currentPath.indexOf(url) === 0;
}

function onClick(url, metrika, e) {
    Metrika.send('Сайдбар сервисов', metrika);

    e.preventDefault();
    Url.open(url);
}

function ServiceSidebar(props) {
    return (
        <Sidebar2
            cls={bServiceSidebar()}
            onToggle={props.onToggle}
            title={i18n('service_page.sidebar.title')}
            role="service"
        >
            {Service.getList(SERVICE_ITEMS).map(item => {
                if (!item.isService || (item.available !== undefined && !item.available)) {
                    return null;
                }

                return (
                    <Sidebar2.MenuItem
                        key={item.id}
                        cls={bServiceSidebar('link')}
                        url={item.settingsLink}
                        active={isActive(item)}
                        onClick={onClick.bind(this, item.settingsLink, item.metrika)}
                        icon={<ServiceIcon cls={bServiceSidebar('icon')} serviceSlug={item.id} />}
                        title={item.title}
                    />
                );
            })}
        </Sidebar2>
    );
}

ServiceSidebar.propTypes = {
    onToggle: PropTypes.func.isRequired,
};

export default ServiceSidebar;
