/* @flow */
import { connect } from 'react-redux';

import React, { PureComponent } from 'react';
import { SectionList } from 'react-native';

import type { User, UserGroup, GlobalState } from '../types';
import { getOwnEmail, getSortedUsers, getUserGroups } from '../selectors';
import {
  getAutocompleteSuggestion,
  getAutocompleteUserGroupSuggestions,
} from '../users/userHelpers';
import { Popup } from '../common';
import UserItem from '../users/UserItem';
import UserGroupItem from '../user-groups/UserGroupItem';

type Props = {
  filter: string,
  onAutocomplete: (name: string) => void,
  ownEmail: string,
  users: User[],
  userGroups: UserGroup[],
};

class PeopleAutocomplete extends PureComponent<Props> {
  props: Props;

  render() {
    const { filter, ownEmail, users, userGroups, onAutocomplete } = this.props;
    const filteredUserGroups = getAutocompleteUserGroupSuggestions(userGroups, filter);
    const filteredUsers: User[] = getAutocompleteSuggestion(users, filter, ownEmail);

    if (filteredUserGroups.length + filteredUsers.length === 0) {
      return null;
    }

    const sections = [
      {
        data: filteredUserGroups,
        renderItem: ({ item }) => (
          <UserGroupItem
            key={item.name}
            name={item.name}
            description={item.description}
            onPress={() => onAutocomplete(`*${item.name}*`)}
          />
        ),
      },
      {
        data: filteredUsers,
        renderItem: ({ item }) => (
          <UserItem
            key={item.user_id}
            fullName={item.full_name}
            avatarUrl={item.avatar_url}
            email={item.email}
            showEmail
            onPress={() => onAutocomplete(`**${item.full_name}**`)}
          />
        ),
      },
    ];

    return (
      <Popup>
        <SectionList
          keyboardShouldPersistTaps="always"
          initialNumToRender={10}
          sections={sections}
        />
      </Popup>
    );
  }
}

export default connect((state: GlobalState) => ({
  ownEmail: getOwnEmail(state),
  users: getSortedUsers(state),
  userGroups: getUserGroups(state),
}))(PeopleAutocomplete);

@@ -733,16 +733,241 @@
 Props;%0A%0A
+  handleUserGroupItemAutocomplete = (name: string): void =%3E %7B%0A    this.props.onAutocomplete(%60*$%7Bname%7D*%60);%0A  %7D;%0A%0A  handleUserItemAutocomplete = (%7B fullName %7D): void =%3E %7B%0A    this.props.onAutocomplete(%60**$%7BfullName%7D**%60);%0A  %7D;%0A%0A
   render
@@ -1022,24 +1022,8 @@
 oups
-, onAutocomplete
  %7D =
@@ -1553,46 +1553,44 @@
 ss=%7B
-() =%3E onAutocomplete(%60*$%7Bitem.name%7D*%60)
+this.handleUserGroupItemAutocomplete
 %7D%0A  
@@ -1900,53 +1900,39 @@
 ss=%7B
-() =%3E onAutocomplete(%60**$%7Bitem.full_name%7D**%60)
+this.handleUserItemAutocomplete
 %7D%0A  

Save new function creation for each item.