import React from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import { ListDimensions } from 'constants/UI';
import { Permissions } from 'constants/Common';
import StoreMixin from 'lib/StoreMixin';

import Url from 'lib/Url';
import { i18n } from 'lib/i18n';
import Metrika from 'lib/metrika';

import AuthStore from 'stores/Auth';
import ApplicationStore from 'stores/Application';
import GroupStore from 'stores/Groups';
import ChunkStore from 'stores/Chunks';
import PermissionStore from 'stores/Permissions';

import GroupActions from 'actions/Group';
import ModalActions from 'actions/Modal';

import Link from 'ui/Link';
import ScrollableList from 'ui/ScrollableList';
import SectionListItem from 'components/SectionListItem';
import CreateForm from 'components/Group/Forms/Create';

const List = React.createClass({

    mixins: [StoreMixin, PureRenderMixin],

    getStoreState() {
        const filter = ApplicationStore.getSubsectionName();
        const userId = AuthStore.getUserId();
        let chunkKey = 'groups/type=generic';

        switch (filter) {
            case 'admin':
                chunkKey += `/admin_uid=${userId}`;
                break;
            case 'member':
                chunkKey += `/member_uid=${userId}`;
                break;
        }

        return {
            filter,
            chunk: ChunkStore.get(chunkKey),
            key: this.hashCode(),
        };
    },

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

    _handleItemClick(item) {
        Metrika.send('Команды', 'Список команд', 'Клик на команду в списке');

        Url.open(Url.getGroupPath('auto', item.getId()));
    },

    _handleAddClick(event) {
        event.preventDefault();

        Metrika.send(
            'Команды', 'Список команд', 'Клик на "Создать команду" при пустом списке',
            Metrika.getUserType()
        );

        ModalActions.open({
            title: i18n('group.new_group'),
            component: CreateForm,
            props: {
                onSubmit: this._handleFormDone,
                onCancel: this._handleFormDone,
            },
        });
    },

    _handleFormDone() {
        ModalActions.close();
    },

    _renderPlaceholder() {
        const subsection = ApplicationStore.getSubsectionName();

        const link = {
            showAll: (
                <Link to={Url.getContextPath('groups')}>
                    {i18n('group.show_all_groups')}
                </Link>
            ),
            createNew: (
                <Link onClick={this._handleAddClick}>
                    {i18n('group.create_group')}
                </Link>
            ),
        };

        switch (subsection) {
            case 'member':
                return (
                    <div className="group-list-placeholder">
                        <p dangerouslySetInnerHTML={{ __html: i18n('group.not_a_member') }} />
                        <p>{link.showAll}</p>
                    </div>
                );

            case 'admin':
                return (
                    <div className="group-list-placeholder">
                        <p dangerouslySetInnerHTML={{ __html: i18n('group.not_an_admin') }} />
                        <p>{link.showAll}</p>
                    </div>
                );

            default:
                if (subsection === 'all' && PermissionStore.contains(Permissions.ADD_GROUPS)) {
                    return (
                        <div className="group-list-placeholder">
                            <p>{link.createNew}</p>
                        </div>
                    );
                }

                return (
                    <div className="group-list-placeholder">
                        <p>{i18n('group.list_empty')}</p>
                    </div>
                );
        }
    },

    _getItems() {
        const chain = ApplicationStore.getObjectChain();
        let selectedFound = false;

        return this.state.chunk.getCollectedItems()
            .map(id => {
                const group = GroupStore.get(id);

                if (!group) {
                    return null;
                }

                const selected = !selectedFound &&
                    chain && chain[0] &&
                    chain[0].id === id && chain[0].type === 'group';

                // отмечаем, что выбранный элемент найден
                // выбранных элементов должно быть не больше одного
                if (selected) {
                    selectedFound = true;
                }

                const component = (
                    <SectionListItem
                        key={id}
                        ref={selected ? 'selectedGroup' : null}
                        primary
                        selected={selected}
                        item={group}
                        onClick={this._handleItemClick}
                    />
                );

                return { component, height: ListDimensions.GROUP_HEIGHT };
            })
            .filter(Boolean);
    },

    _fetchItems() {
        const { chunk, busy, filter } = this.state;

        if (chunk.isLast() || busy) {
            return;
        }

        this.setState({ busy: true });

        const requestOptions = {
            page: chunk.getPage() + 1,
            type: 'generic',
            ordering: 'name',
        };

        switch (filter) {
            case 'admin':
                requestOptions.admin_uid = AuthStore.getUserId();
                break;
            case 'member':
                requestOptions.member_uid = AuthStore.getUserId();
                break;
        }

        return GroupActions.getList(requestOptions)
            .then(() => {
                this.setState({ busy: false });
            })
            .catch(() => {
                this.setState({ busy: false });
            });
    },

    render() {
        const items = this._getItems();

        if (!items.length) {
            return (
                <div className="group-list">
                    {this._renderPlaceholder()}
                </div>
            );
        }

        return (
            <ScrollableList
                key={this.state.filter}
                className="group-list section-scrollpane"
                items={items}
                onBottomHit={this._fetchItems}
                busyBottom={this.state.busy}
                scrollTo={this.state.scrollTo}
                ref="list"
            />
        );
    },

});

List.propTypes = {

};

export default List;
