import PropTypes from 'prop-types';
import React from 'react';
import Picker from 'ui-components/lib/Picker';
import { ActionTypes } from 'constants/Common';
import Unit from 'ui/Unit';
import SuggestService from 'services/suggest';

import dispatcher from 'dispatcher';

const SuggestPicker = React.createClass({

    _getSuggestSource(text, next) {
        const { limit, type } = this.props;
        const members = this.refs.picker.value();

        const suggestParams = { text, limit };

        if (type) {
            suggestParams.types = [type];
        }

        SuggestService.search(suggestParams, next, item =>
            !members.some(member =>
                member.getType() === item.type && member.getId() === item.id));
    },

    _renderSuggestion(payload) {
        const item = payload.item;

        return (
            <Unit
                avatar={item.getAvatar()}
                title={item.getName()}
                description={item.getDescription()}
            />
        );
    },

    _renderItem(item, index, selectedIndex) {
        return (
            <Picker.Item
                avatar={item.getAvatar()}
                type={item.getType()}
                title={item.getName()}
                selected={index === selectedIndex}
            />
        );
    },

    _handleFocus() {
        setTimeout(() => {
            dispatcher.dispatch(ActionTypes.SUGGEST_LIST_OPEN, { id: this.props.id });
        }, 0);
    },

    _handleDone() {
        setTimeout(() => {
            dispatcher.dispatch(ActionTypes.SUGGEST_LIST_CLOSED, { id: this.props.id });
        }, 0);
    },

    value() {
        return this.refs.picker.value();
    },

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

    render() {
        let source = null;

        if (this.props.suggest) {
            source = this._getSuggestSource;
        }

        return (
            <Picker
                {...this.props}
                ref="picker"
                source={source}
                renderItem={this._renderItem}
                renderSuggestion={this._renderSuggestion}
                onFocus={this._handleFocus}
                onSuggestSelect={this._handleDone}
                onBlur={this._handleDone}
                placeholder={this.props.placeholder}
                value={this.props.value}
            />
        );
    },
});

SuggestPicker.defaultProps = {
    limit: 3,
};

SuggestPicker.propTypes = {
    limit: PropTypes.number,
    suggest: PropTypes.bool,
    type: PropTypes.oneOf([
        'department',
        'group',
        'user',
    ]),
};

export default SuggestPicker;
