import PropTypes from 'prop-types';
import React from 'react';
import { Permissions } from 'constants/Common';
import { i18n } from 'lib/i18n';
import Metrika from 'lib/metrika';
import PermissionStore from 'stores/Permissions';

import Form from 'ui/Form';
import Input from 'ui/Input';
import SuggestPicker from 'components/SuggestPicker';

function isDisabled(user) {
    return !PermissionStore.contains(Permissions.EDIT_USER_INFO, user);
}

const Department = React.createClass({

    getInitialState() {
        const { user } = this.props;
        let { department } = this.props;

        if (!department && user) {
            department = user.getDepartment();
        }

        return { department };
    },

    _handleDepartmentChange(items) {
        Metrika.send('Карточка пользователя', 'Редактирование', 'Смена департамента');

        this.setState({ department: items[0] || null });
    },

    render() {
        const { department } = this.state;
        const { user, errors } = this.props;

        let value;

        if (isDisabled(user)) {
            value = (
                <Input
                    val={department ? department.getName() : null}
                    size="m"
                    width="available"
                    disabled
                />
            );
        } else {
            value = (
                <SuggestPicker
                    onChange={this._handleDepartmentChange}
                    suggest
                    multiple={false}
                    size="m"
                    type="department"
                    value={department ? [department] : []}
                    width="available"
                />
            );
        }

        return (
            <Form.Item label={i18n('user.department')} errors={errors.department}>
                <input
                    type="hidden"
                    name="department_id"
                    value={department ? department.getId() : ''}
                />
                {value}
            </Form.Item>
        );
    },
});

Department.propTypes = {
    user: PropTypes.object,
    department: PropTypes.object,
    errors: PropTypes.object,
};

Department.defaultProps = {
    errors: {},
};

export default Department;
