import React from 'react';
import { View, FlatList } from 'react-native';

import { fetchAuth, fetchTagferApi } from '../../utils/fetch';
import { showFlashErrorMessage } from '../../utils/errorHandler';

import colors from '../../config/colors.json';
import endpoints from '../../config/apiEndpoints';
import UserListItem from '../../components/new/UserListItem';

export default class SuggestedContactsScreen extends React.Component {
  static navigationOptions = ({ navigation }) => {
    const title = navigation.getParam('title', 'Suggested');
    return { title };
  }

  constructor(props) {
    super(props);
    this.state = {
      users: [],
      loading: true
    };
  }

  componentDidMount() {
    this.onLoad();
  }

  // Load suggested contacts
  async onLoad() {
    const resp = await fetchAuth(endpoints.suggestProfiles);
    this.setState({ loading: false, users: resp.profiles || [] });

    if (resp.error) {
      return showFlashErrorMessage(resp.error);
    }
    
    this.updateTitle();
  }

  // WARN: this might break as we are mutating state
  async onConnect(index) {
    const response = await fetchTagferApi(endpoints.sendConnectionRequest(1), { toTagferId: this.state.users[index].tagferId });
    if (response.error) {
      return showFlashErrorMessage(response.error);
    }

    this.state.users.splice(index, 1);
    this.updateTitle();

    if (this.state.users.length === 0) {
      this.onLoad();
    }
  }

  // Update count in title
  updateTitle() {
    let count = this.state.users.length;
    if (count > 100) { count = '99+'; }

    this.props.navigation.setParams({ title: `Suggested(${count})` });
  }

  // Render a single entry in the list
  renderItem(profile, index) {
    return <UserListItem profile={profile} onPress={() => this.onConnect(index)} />;
  }

  render() {
    return (
      <View style={{ flex: 1, backgroundColor: colors.offWhite }}>
        {/* SUGGESTED CONTACTS */}
        <FlatList 
          data={this.state.users}
          extraData={this.state}
          renderItem={({ item, index }) => this.renderItem(item, index)}
          keyExtractor={(item) => item.tagferId}
          style={{ flex: 1, marginHorizontal: 10, marginTop: 10, borderRadius: 2 }}
          refreshing={this.state.loading}
          onRefresh={() => this.onLoad()}
        />
      </View>
    );
  }
}
