import _ from 'lodash';
import PropTypes from 'prop-types';
import React from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import { ListDimensions } from 'constants/UI';
import StoreMixin from 'lib/StoreMixin';

import Url from 'lib/Url';
import Metrika from 'lib/metrika';

import ApplicationStore from 'stores/Application';
import GroupStore from 'stores/Groups';
import UserStore from 'stores/Users';
import UIStore from 'stores/UI';
import UIActions from 'actions/UI';

import SectionListItem from 'components/SectionListItem';
import ScrollableList from 'ui/ScrollableList';

const REF_MAP = {
    admins: 'selectedAdmin',
    members: 'selectedMember',
};

const METRIKA_MAP = {
    admins: 'Список администраторов',
    members: 'Список пользователей',
    click: {
        department: 'Клик в отдел',
        user: 'Клик в пользователя',
        group: 'Клик в команду',
    },
};

const MemberList = React.createClass({

    mixins: [StoreMixin, PureRenderMixin],

    getStoreState() {
        return {
            key: this.hashCode(ApplicationStore, GroupStore, UserStore, UIStore),
            editable: UIStore.isGroupListEditable(this.props),
        };
    },

    componentDidMount() {
        this.subscribe([ApplicationStore, GroupStore, UserStore, UIStore]);
    },

    _handleItemClick(item) {
        const { id, type } = this.props;
        const groupMember = {
            id: item.getId(), type: item.getType(), role: type,
        };

        Metrika.send(
            'Команды', 'Карточка команды', METRIKA_MAP[type],
            METRIKA_MAP.click[groupMember.type], Metrika.getUserType()
        );

        Url.open(Url.getGroupMemberPath('auto', id, groupMember));
    },

    _handleItemChange(item) {
        const { id, type } = this.props;
        let selectedMembers = UIStore.getSelectedGroupMembers(id, type) || [];

        if (selectedMembers.some(member => member.equals(item))) {
            selectedMembers = selectedMembers.filter(member => !member.equals(item));
        } else {
            selectedMembers = selectedMembers.concat(item);
        }

        UIActions.selectGroupMembers({ id, type, list: selectedMembers });
    },

    _getItems() {
        const { id, type } = this.props;
        const { editable } = this.state;
        const group = GroupStore.get(id);

        if (!group) {
            return [];
        }

        const selectedMembers = UIStore.getSelectedGroupMembers(id, type) || [];

        const displayedObject = ApplicationStore.getSecondaryObject();
        // (admins|members) => group.(getAdmins|getMembers)()
        const items = group[`get${_.capitalize(type)}`]();
        let selectedFound = false;

        return items.map(item => {
            if (!item) {
                return null;
            }

            const itemId = item.getId();
            const itemType = item.getType();

            const checked = selectedMembers.includes(item);

            const selected = !selectedFound && displayedObject &&
                itemType === displayedObject.type &&
                itemId === displayedObject.id &&
                // если выбран участник, то подсвечиваем только в колонке участников;
                // такой же элемент списка в колонке админов не подсвечиваем
                type === displayedObject.path[0];

            if (selected) {
                selectedFound = true;
            }

            const component = (
                <SectionListItem
                    key={`${itemType}-${itemId}`}
                    ref={selected ? REF_MAP[type] : null}
                    selected={selected}
                    editable={editable}
                    checked={checked}
                    item={item}
                    onClick={this._handleItemClick}
                    onChange={this._handleItemChange}
                />
            );

            return { component, height: ListDimensions.GROUP_MEMBER_HEIGHT };
        });
    },

    render() {
        return (
            <ScrollableList
                className="group-list section-scrollpane"
                items={this._getItems()}
                ref="list"
            />
        );
    },

});

MemberList.propTypes = {
    id: PropTypes.string,
    type: PropTypes.oneOf(['admins', 'members']),
};

export default MemberList;
