import PropTypes from 'prop-types';
import React from 'react';
import classSet from 'classnames';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import StoreMixin from 'lib/StoreMixin';

import DepartmentStore from 'stores/Departments';
import ApplicationStore from 'stores/Application';

import timer from 'lib/timer';
import EditableHeader from './EditableHeader';
import CardHeader from './CardHeader';
import List from './List';
import FlatList from './FlatList';
import Footer from './Footer';

import './index.css';

const Department = React.createClass({

    mixins: [StoreMixin, PureRenderMixin],

    getStoreState() {
        return {
            key: this.hashCode(DepartmentStore),
            stateId: ApplicationStore.getStateId(),
        };
    },

    componentDidMount() {
        this.subscribe([ApplicationStore, DepartmentStore]);
        this._scrollToSelected();

        timer.stop('create_department');
    },

    componentDidUpdate(prevProps, prevState) {
        if (this.state.stateId !== prevState.stateId) {
            this._scrollToSelected();
        }
    },

    _getSelectedItem() {
        const list = this.refs.list;

        if (!list) {
            return null;
        }

        const selectedItem = list.refs.selectedDepartment ||
            list.refs.selectedUser;

        return selectedItem;
    },

    _scrollToSelected() {
        setTimeout(() => {
            const selectedItem = this._getSelectedItem();

            if (selectedItem) {
                this.setState({ scrollTo: selectedItem });
            }
        }, 0);
    },

    render() {
        const { id, flat } = this.props;
        const department = DepartmentStore.get(id);

        if (!department) {
            return null;
        }

        let HeaderComponent = EditableHeader;
        let ListComponent = List;

        if (flat) {
            HeaderComponent = CardHeader;
            ListComponent = FlatList;
        }

        const className = classSet({
            'department-section': true,
            'root-department-section': department.isRoot(),
            'column-section': true,
            section: true,
        });

        return (
            <div className={className}>
                <HeaderComponent id={id} />
                <div className="department-body section-body">
                    <ListComponent id={id} ref="list" scrollTo={this.state.scrollTo} />
                </div>
                <Footer id={id} />
            </div>
        );
    },

});

Department.propTypes = {
    id: PropTypes.string,
    flat: PropTypes.bool,
};

export default Department;
