import React, { Component } from 'react';
import _ from 'lodash';
import { block } from 'bem-cn';
import PropTypes from 'prop-types';

import storage from 'services/storage';

import Scrollable from 'ui/Scrollable';

import Toggler from './Toggler';
import MenuItem from './MenuItem';

import './index.css';

const bSidebarMenu = block('sidebar2');

class Sidebar2 extends Component {
    constructor(props) {
        super(props);

        this.state = {
            collapsed: storage.local.getValue(this._getStorageKey()) || false,
        };

        this._onToggle = this._onToggle.bind(this);
    }

    _getStorageKey() {
        const { role } = this.props;

        return role ? `${role}_sidebar_collapsed` : 'sidebar_collapsed';
    }

    _onToggle() {
        const collapsed = !this.state.collapsed;

        storage.local.setValue(this._getStorageKey(), collapsed);

        this.setState({ collapsed });
        this.props.onToggle(collapsed);
    }

    render() {
        const { collapsed } = this.state;
        const { children, title } = this.props;

        return (
            <Scrollable contentClassName={bSidebarMenu({ collapsed }).toString()}>
                <div className={bSidebarMenu('header')}>
                    <h2 className={bSidebarMenu('title')}>
                        {title}
                    </h2>
                    <Toggler cls={bSidebarMenu('toggler')} onToggle={this._onToggle} />
                </div>
                {children}
            </Scrollable>
        );
    }
}

Sidebar2.propTypes = {
    onToggle: PropTypes.func.isRequired,
    role: PropTypes.string,
    title: PropTypes.string,
};

_.extend(Sidebar2, {
    MenuItem,
});

export default Sidebar2;
