import PropTypes from 'prop-types';
import React from 'react';
import { i18n } from 'lib/i18n';
import Form from 'ui/Form';
import SuggestPicker from 'components/SuggestPicker';
import AuthStore from 'stores/Auth';

const Admins = React.createClass({

    getInitialState() {
        const { value, group } = this.props;
        let defaultValue = [];

        if (!group && AuthStore.isInternal()) {
            defaultValue = [AuthStore.getUser()];
        }

        return { items: value.length ? value : defaultValue };
    },

    focus() {
        this.refs.picker.focus();
    },

    _handlePickerChange(items) {
        const { onChange } = this.props;

        this.setState({ items });

        if (onChange) {
            onChange(items);
        }
    },

    _serialize() {
        return JSON.stringify(this.state.items.map(
            item => ({ id: String(item.getId()) })
        ));
    },

    render() {
        const { group, errors } = this.props;
        const { items } = this.state;

        return (
            <Form.Item
                label={i18n('group.admins')}
                errors={errors.admins}
                required
            >
                <input
                    type="hidden"
                    name={group ? 'selected_admins' : 'admins'}
                    value={this._serialize()}
                />
                <SuggestPicker
                    id="group-form-admins"
                    ref="picker"
                    suggest
                    multiline
                    onChange={this._handlePickerChange}
                    type="user"
                    value={items}
                    width="available"
                />
            </Form.Item>
        );
    },

});

Admins.propTypes = {
    group: PropTypes.object,
    value: PropTypes.array,
    errors: PropTypes.object,
    onChange: PropTypes.func,
};

Admins.defaultProps = {
    value: [],
    errors: {},
};

export default Admins;
