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 Metrika from 'lib/metrika';
import Url from 'lib/Url';

import ApplicationStore from 'stores/Application';
import DepartmentStore from 'stores/Departments';
import UserStore from 'stores/Users';
import ChunkStore from 'stores/Chunks';
import UserActions from 'actions/User';

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

const FlatList = React.createClass({

    mixins: [StoreMixin, PureRenderMixin],

    getStoreState() {
        return {
            chunk: ChunkStore.get(`users/recursive_department_id=${this.props.id}`),
            key: this.hashCode(),
        };
    },

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

    _handleItemClick(item) {
        Metrika.send('Структура', 'Клик в отдел');

        Url.open(item.getUrl());
    },

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

                if (!user) {
                    return null;
                }

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

                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,
            recursive_department_id: this.props.id,
            ordering: 'name',
        };

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

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

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

});

FlatList.propTypes = {
    id: PropTypes.string,
};

export default FlatList;
