import React from 'react';
import { View, Text, TouchableOpacity, FlatList } from 'react-native';
import { ListItem, Icon } from 'react-native-elements';

import { fetchTagferApi } from '../../utils/fetch';

import TagferAvatar from '../../components/new/TagferAvatar';
import colors from '../../config/colors.json';
import endpoints from '../../config/apiEndpoints';
import { showFlashErrorMessage } from '../../utils/errorHandler';

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

  constructor(props) {
    super(props);
    this.state = {
      filter: 'rcvd',
      currRequests: [],
      loading: false
    };

    this.rcvdRequests = [];
    this.sentRequests = [];
    this.onRcvdPress = this.onRcvdPress.bind(this);
    this.onSentPress = this.onSentPress.bind(this);
  }

  componentDidMount() {
    this.onLoad();
  }

  onRcvdPress() {
    this.setState({ filter: 'rcvd', currRequests: this.rcvdRequests });
  }

  onSentPress() {
    this.setState({ filter: 'sent', currRequests: this.sentRequests });
  }

  onAccept(index) {
    const fromTagferId = this.rcvdRequests[index].tagferId;
    const fromProfileN = this.rcvdRequests[index].profileN;
    const response = fetchTagferApi(endpoints.acceptConnectionRequest(1), { fromTagferId, fromProfileN });

    if (response.error) { 
      return showFlashErrorMessage(response.error);
    }

    this.rcvdRequests.splice(index, 1);
    this.setState({ currRequests: this.rcvdRequests });
    this.updateTitle();
  }

  async onReject(index) {
    const { filter } = this.state;
    const fromTagferId = filter === 'rcvd' ? this.rcvdRequests[index].tagferId : undefined;
    const toTagferId = filter === 'sent' ? this.sentRequests[index].tagferId : undefined;
    const response = await fetchTagferApi(endpoints.removeConnectionRequest, { fromTagferId, toTagferId });

    if (response.error) {
      return showFlashErrorMessage(response.error);
    }

    if (this.state.filter === 'rcvd') {
      this.rcvdRequests.splice(index, 1);
      this.setState({ currRequests: this.rcvdRequests });
    } else {
      this.sentRequests.splice(index, 1);
      this.setState({ currRequests: this.sentRequests });
    }

    this.updateTitle();
  }

  async onLoad() {
    this.setState({ loading: true });
    const response = await fetchTagferApi(endpoints.getConnectionRequests);
    
    if (response.error) {
      this.setState({ loading: false });
      return showFlashErrorMessage(response.error);
    }

    this.rcvdRequests = response.received;
    this.sentRequests = response.sent;
    this.updateTitle();

    const currRequests = this.state.filter === 'rcvd' ? this.rcvdRequests : this.sentRequests;
    this.setState({ currRequests, loading: false });
  }

  updateTitle() {
    let numOfRequests = this.rcvdRequests.length + this.sentRequests.length;
    if (numOfRequests > 100) { numOfRequests = '99+'; }

    this.props.navigation.setParams({ title: `Unconfirmed(${numOfRequests})` });
  }

  // Render a single entry in the list
  renderItem(profile, index) {
    return (
      <RequestListItem
        type={this.state.filter}
        profile={profile}
        onAccept={() => this.onAccept(index)}
        onReject={() => this.onReject(index)}
      />
    );
  }

  render() {
    return (
      <View style={styles.container}>
        <FilterButtons
          filter={this.state.filter}
          rcvdCount={this.rcvdRequests.length}
          sentCount={this.sentRequests.length}
          onRcvdPress={this.onRcvdPress}
          onSentPress={this.onSentPress}
        />
        <FlatList
          data={this.state.currRequests}
          extraData={this.state}
          renderItem={({ item, index }) => this.renderItem(item, index)}
          keyExtractor={(item) => item.tagferId}
          style={{ flex: 1, marginHorizontal: 10, marginTop: 10, borderRadius: 5 }}
          refreshing={this.state.loading}
          onRefresh={() => this.onLoad()}
        />
      </View>
    );
  }
}

const FilterButtons = ({ filter, rcvdCount = 0, sentCount = 0, onRcvdPress, onSentPress }) => {
  let rcvdButtonStyle;
  let rcvdButtonText;
  let sentButtonStyle;
  let sentButtonText;

  if (filter === 'sent') {
    rcvdButtonStyle = styles.rcvdButtonNotSelected;
    sentButtonStyle = styles.sentButtonSelected;
    rcvdButtonText = styles.notSelectedText;
    sentButtonText = styles.selectedText;
  } else {
    rcvdButtonStyle = styles.rcvdButtonSelected;
    sentButtonStyle = styles.sentButtonNotSelected;
    rcvdButtonText = styles.selectedText;
    sentButtonText = styles.notSelectedText;
  }

  return (
    <View style={{ flexDirection: 'row', justifyContent: 'space-between', marginTop: 10 }}>
      <TouchableOpacity style={rcvdButtonStyle} onPress={onRcvdPress}>
        <Text style={rcvdButtonText}>Requests received ({rcvdCount})</Text>
      </TouchableOpacity>

      <TouchableOpacity style={sentButtonStyle} onPress={onSentPress}>
        <Text style={sentButtonText}>Requests sent ({sentCount})</Text>
      </TouchableOpacity>
    </View>
  );
};

const RequestListItem = ({ type, profile, onAccept, onReject }) => {
  const { tagferId, fullName, jobTitle, companyName, photoURL } = profile;
  const subtitle = `@${tagferId}\n${jobTitle} at ${companyName}`;

  return (
    <ListItem
      roundAvatar
      avatar={<TagferAvatar size='medium' photoURL={photoURL} color={colors.lightGrey} />}
      title={fullName}
      subtitle={subtitle}
      subtitleNumberOfLines={3}
      subtitleStyle={{ fontSize: 12, fontWeight: 'normal' }}
      titleStyle={{ fontSize: 16, color: 'black' }}
      rightIcon={<ActionButtons type={type} onAccept={onAccept} onReject={onReject} />}
      containerStyle={{ backgroundColor: 'white' }}
    />
  );
};

const ActionButtons = ({ type, onAccept, onReject }) => {
  const sentActionButtons = (
    <Icon
      name='ios-close-circle-outline'
      type='ionicon' size={45}
      color='#7389AE'
      onPress={onReject}
    />
  );

  const rcvdActionButtons = (
    <View style={{ flexDirection: 'row' }}>
      <Icon
        name='ios-close-circle-outline'
        type='ionicon' size={45}
        color='#7389AE'
        containerStyle={{ marginRight: 10 }}
        onPress={onReject}
      />
      <Icon
        name='ios-checkmark-circle-outline'
        type='ionicon' size={45}
        color={colors.addGreen}
        onPress={onAccept}
      />
    </View>
  );

  return type === 'sent' ? sentActionButtons : rcvdActionButtons;
};

const styles = {
  container: {
    flex: 1,
    backgroundColor: colors.offWhite
  },
  rcvdButtonSelected: {
    marginLeft: 40,
    height: 30,
    paddingHorizontal: 15,
    justifyContent: 'center',
    borderRadius: 15,
    backgroundColor: '#AAAFC4'
  },
  rcvdButtonNotSelected: {
    marginLeft: 40,
    height: 30,
    paddingHorizontal: 15,
    justifyContent: 'center',
    borderRadius: 15
  },
  sentButtonSelected: {
    marginRight: 40,
    height: 30,
    paddingHorizontal: 15,
    justifyContent: 'center',
    borderRadius: 15,
    backgroundColor: '#AAAFC4'
  },
  sentButtonNotSelected: {
    marginRight: 40,
    height: 30,
    paddingHorizontal: 15,
    justifyContent: 'center',
    borderRadius: 15
  },
  selectedText: {
    fontSize: 13,
    fontWeight: 'bold',
    color: 'white'
  },
  notSelectedText: {
    fontSize: 14,
    fontWeight: 'normal',
    color: '#6A6A6A'
  }
};
