import PropTypes from 'prop-types';
import React from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import StoreMixin from 'lib/StoreMixin';
import ApplicationStore from 'stores/Application';

import MemberList from './MemberList';
import FlatMemberList from './FlatMemberList';

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

const Body = React.createClass({

    mixins: [StoreMixin, PureRenderMixin],

    getStoreState() {
        return { stateId: ApplicationStore.getStateId() };
    },

    componentDidMount() {
        this.subscribe(ApplicationStore);
        this._scrollToSelected();
        this._mounted = true;
    },

    componentWillUnmount() {
        this._mounted = false;
    },

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

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

        return list ? list.refs[REF_MAP[this.props.type]] : null;
    },

    _scrollToSelected() {
        setTimeout(() => {
            if (this._mounted) {
                this.setState({ scrollTo: this._getSelectedItem() });
            }
        }, 0);
    },

    render() {
        const { id, type, flat } = this.props;
        let list;

        const listProps = { id, ref: 'list', scrollTo: this.state.scrollTo };

        if (flat) {
            list = <FlatMemberList {...listProps} />;
        } else {
            list = <MemberList {...listProps} type={type} />;
        }

        return (
            <div className="group-body section-body">
                {list}
            </div>
        );
    },

});

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

export default Body;
