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

const Members = React.createClass({

    getInitialState() {
        return { items: this.props.value };
    },

    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: item.getId(), type: item.getType() })
        ));
    },

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

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

});

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

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

export default Members;
