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 PICKER_TYPE_MAP = {
    users: 'user',
    departments: 'department',
};

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 { type, multiple, errors } = this.props;
        const { items } = this.state;
        // type: users | departments

        return (
            <Form.Item
                label={i18n(`department.${type}`)}
                errors={errors.members}
            >
                <input type="hidden" name="members" value={this._serialize()} />
                <SuggestPicker
                    id="department-form-members"
                    ref="picker"
                    suggest
                    type={PICKER_TYPE_MAP[type]}
                    multiple={multiple}
                    multiline={multiple}
                    onChange={this._handlePickerChange}
                    value={items}
                    width="available"
                />
            </Form.Item>
        );
    },

});

Members.propTypes = {
    type: PropTypes.string,
    multiple: PropTypes.bool,
    value: PropTypes.array,
    errors: PropTypes.object,
    onChange: PropTypes.func,
};

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

export default Members;
