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

import PermissionStore from 'stores/Permissions';
import ApplicationStore from 'stores/Application';
import UserStore from 'stores/Users';

import Close from 'components/Group/Controls/CloseSubsection';
import { i18n } from 'lib/i18n';
import timer from 'lib/timer';
import Identity from './Identity';
import Contacts from './Contacts';
import Department from './Department';
import Groups from './Groups';
import Services from './Services';
import Edit from './Controls/Edit';

import './index.css';

const Section = React.createClass({

    mixins: [StoreMixin, PureRenderMixin],

    getStoreState() {
        const { id } = this.props;
        const user = UserStore.get(id);
        const isGroupLayout = ApplicationStore.getPrimaryType() === 'groups';

        return {
            user,
            isGroupLayout,
            editableInformation: user && PermissionStore.allowsUserEditing(user) && !isGroupLayout,
            editableAvatar: user && PermissionStore.allowsUserAvatarEditing(user),
        };
    },

    componentDidMount() {
        this.subscribe([UserStore, PermissionStore, ApplicationStore]);

        timer.stop('create_user');
    },

    render() {
        const { id } = this.props;
        const { user, isGroupLayout, editableInformation, editableAvatar } = this.state;

        if (!user) {
            return null;
        }

        let editingControls;
        let closeButton;

        if (editableInformation) {
            editingControls = (
                <Edit
                    id={id}
                    title={i18n('user.action_description.edit', {
                        name: user.getName(),
                    })}
                />
            );
        }

        if (isGroupLayout) {
            closeButton = <Close />;
        }

        return (
            <div className="user-section card-section section">
                <div className="section-body">
                    <Scrollable>
                        {editingControls}
                        {closeButton}
                        <Identity user={user} editableAvatar={editableAvatar} />
                        <Contacts id={id} />
                        <Department id={id} />
                        <Groups id={id} />
                        <Services id={id} />
                    </Scrollable>
                </div>
            </div>
        );
    },

});

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

export default Section;
