import _ from 'lodash';
import React from 'react';
import { ListDimensions } from 'constants/UI';
import StoreMixin from 'lib/StoreMixin';

import { i18n } from 'lib/i18n';
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 ChunkStore from 'stores/Chunks';
import UIStore from 'stores/UI';

import UIActions from 'actions/UI';
import ModalActions from 'actions/Modal';
import UserActions from 'actions/User';

import ScrollableList from 'ui/ScrollableList';
import SectionListItem from 'components/SectionListItem';
import Link from 'ui/Link';
import AddForm from './Forms/Add';

const AdminList = React.createClass({

    mixins: [StoreMixin],

    getStoreState() {
        const chunk = ChunkStore.get('users/role=admin');

        return {
            chunk,
            key: this.hashCode(),
            editable: UIStore.isOrganizationAdminListEditable(this.props),
            initializing: ApplicationStore.isBusy() || !chunk.getPage(),
        };
    },

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

    componentWillUpdate(nextProps, nextState) {
        const { selectedItems } = this.state;

        if (!nextState.editable && selectedItems && selectedItems.length) {
            this._reset();
        }
    },

    shouldComponentUpdate() {
        return !this.state.initializing;
    },

    _reset() {
        this.setState({ selectedItems: [] });
    },

    _handleItemClick(item) {
        Metrika.send(
            'Настройки организации', 'Администраторы',
            'Клик по админу в списке'
        );
        Url.open(Url.getOrgAdminPath(item.getId()));
    },

    _handleItemChange(item, selected) {
        const { selectedItems } = this.state;
        const initialCount = selectedItems.length;

        if (selected) {
            selectedItems.push(item);
        } else {
            _.remove(selectedItems, storedItem => storedItem.equals(item));
        }

        if (selectedItems.length !== initialCount) {
            this.setState({ selectedItems });
            UIActions.selectOrganizationAdmins({ list: selectedItems });
        }
    },

    _getItems() {
        const { chunk, editable, selectedItems } = this.state;

        return chunk.getCollectedItems()
            .map(id => {
                const user = UserStore.get(id);

                if (!user) {
                    return null;
                }

                const checked = Boolean(_.find(selectedItems, item => item.equals(user)));

                const component = (
                    <SectionListItem
                        key={id}
                        editable={editable}
                        checked={checked}
                        item={user}
                        onClick={this._handleItemClick}
                        onChange={this._handleItemChange}
                    />
                );

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

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

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

        this.setState({ busy: true });

        const requestOptions = {
            page: chunk.getPage() + 1,
        };

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

    _handleAddClick(event) {
        event.preventDefault();

        Metrika.send(
            'Настройки организации', 'Администраторы',
            'Клик по добавлению в подсказке в пустом списке'
        );

        ModalActions.open({
            title: i18n('organization_admins.new_admins'),
            component: AddForm,
            props: {
                onSubmit: this._handleFormDone,
                onCancel: this._handleFormDone,
            },
        });
    },

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

    _renderPlaceholder() {
        if (this.state.initializing) {
            return null;
        }

        const addAdmin = (
            <Link onClick={this._handleAddClick}>
                {i18n('organization_admins.action.add_admin')}
            </Link>
        );

        return (
            <div className="admin-list-placeholder">
                <p>{i18n('organization_admins.empty_list')}</p>
                <p>{addAdmin}</p>
            </div>
        );
    },

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

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

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

});

export default AdminList;
