import _ from 'lodash';
import PropTypes from 'prop-types';
import React from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import Button from 'react-bem-components/lib/Button';
import { i18n } from 'lib/i18n';
import Metrika from 'lib/metrika';

import Form from 'ui/Form';
import FormMixin from 'lib/FormMixin';

import userValidator from 'validation/user';
import UserActions from 'actions/User';
import UserStore from 'stores/Users';
import PermissionStore from 'stores/Permissions';
import Avatar from './Components/Avatar';
import Identity from './Components/Identity';
import Contacts from './Components/Contacts';
import Department from './Components/Department';

import filterInput from './filterInput';

import './index.css';

const NOT_ADMIN_USER_FIELDS = ['contacts', 'groups', 'birthday'];

const Update = React.createClass({

    mixins: [PureRenderMixin, FormMixin],

    getInitialState() {
        return { errors: userValidator.getErrors() };
    },

    componentWillReceiveProps() {
        this.setState(this.getInitialState());
    },

    _handleFormSubmit(data) {
        const user = UserStore.get(this.props.id);

        // Если текущий пользователь не имеет право редактировать все поля
        // то нужно оставить только поля доступные пользователю(NOT_ADMIN_USER_FIELDS)
        // иначе директория может ответ 403 ошибкой
        if (!PermissionStore.allowsFullUserEditing(user)) {
            data = _.pick(data, NOT_ADMIN_USER_FIELDS);
        }

        if (this._use(userValidator, filterInput)._validate(data)) {
            Metrika.send('Карточка пользователя', 'Редактирование', 'Сохранить');

            return this._submit(UserActions.updateUser(data, this.props.id), {
                success: i18n('user.status.updated'),
                failure: i18n('user.status.failed_to_update'),
            });
        }
    },

    render() {
        const { id, onCancel } = this.props;
        const user = UserStore.get(id);
        const errors = this.state.errors.toJS();

        return (
            <Form
                className="update-user-form user-form form"
                onSubmit={this._handleFormSubmit}
                autoComplete={false}
            >

                <Avatar user={user} />
                <Identity user={user} errors={errors} />
                <Form.Separator />
                <Contacts user={user} errors={errors} />
                <Department user={user} errors={errors} />
                <Form.Error value={errors._common} mod="standalone" />

                <Form.Buttons mod="aligned">
                    <Button
                        text={i18n('common.action.save')}
                        view="action"
                        type="submit"
                    />
                    <Button
                        text={i18n('common.action.cancel')}
                        name="cancel"
                        onClick={onCancel}
                    />
                </Form.Buttons>
            </Form>
        );
    },
});

Update.propTypes = {
    id: PropTypes.string,
    onSubmit: PropTypes.func,
    onCancel: PropTypes.func,
};

export default Update;
