import React from 'react';
import { Alert, Dimensions, Text, View, FlatList, TouchableOpacity, Platform } from 'react-native';
import { Button, CheckBox } from 'react-native-elements';
import OpenAppSettings from 'react-native-app-settings';
import Permissions from 'react-native-permissions';
import Contacts from 'react-native-contacts';

import { strings } from '../../locales/i18n';
import { fetchAuth } from '../../utils/fetch';

import colors from '../../config/colors.json';
import errors from '../../config/errors';
import endpoints from '../../config/apiEndpoints';
import ContactListItem from '../../components/lists/ContactListItem';


export default class SignupScreenFive extends React.Component {
  static navigationOptions = {
    title: strings('contact.importScreen_title'),
    headerStyle: { borderBottomWidth: 0, backgroundColor: colors.offWhite },
    headerTintColor: '#0D497E',
    headerRight: <Text style={{ color: colors.middleGrey, marginRight: 5 }}>5/6</Text>
  };

  constructor(props) {
    super(props);
    this.state = {
      allContacts: [],
      selectedContacts: new Map()
    };

    this.onSelectAll = this.onSelectAll.bind(this);
    this.fetchContacts();
  }

  // Handles when the user presses on the select all button
  onSelectAll() {
    const { allContacts } = this.state;
    const selectedContacts = new Map();
    if (this.state.selectedContacts.size === 0) {
      for (let i = 0; i < allContacts.length; i++) {
        selectedContacts.set(i, allContacts[i].phoneNumbers);
      }
    }

    this.setState({ selectedContacts });
  }

  // When a user clicks on a single contact
  onSelectContact(index) {
    this.setState((state) => {
      const selectedContacts = new Map(state.selectedContacts);
      if (selectedContacts.has(index)) {
        selectedContacts.delete(index);
      } else {
        const phoneNumbers = state.allContacts[index].phoneNumbers;
        selectedContacts.set(index, phoneNumbers);
      }

      return { selectedContacts };
    });
  }

  // Sends the request and navigates the user to next page. 
  onSaveButtonPress() {
    const { selectedContacts } = this.state;
    const phoneNumbers = [];
    for (const record of selectedContacts.values()) {
      phoneNumbers.push(...record.map(entry => entry.number));
    }

    fetchAuth(endpoints.findUsersByPhone, { phoneNumbers })
    .then(res => console.log(res))
    .catch(() => console.log(errors.APP_NETWORK_ERROR));

    this.props.navigation.navigate('signup6');
  }

  // BEGIN: Fetch contacts
  getContacts() {
    Contacts.getAllWithoutPhotos((error, contacts) => {
      if (error) { 
        this.props.navigation.navigate('signup6');
      } else {
        const selectedContacts = new Map();
        for (let i = 0; i < contacts.length; i++) {
          selectedContacts.set(i, contacts[i].phoneNumbers);
        }
      
        this.setState({ allContacts: contacts, selectedContacts });
      }
    });
  }

  requestPermissions() {
    Permissions.request('contacts').then(permission => {
      if (permission === 'authorized') return this.getContacts();
      this.props.navigation.navigate('signup6');
    });
  }

  createSettingsAlert() {
    Alert.alert(
      'Contacts Access Denied', 
      'To enable access, tap Settings and turn on Contacts', 
      [
        { text: 'Cancel', onPress: () => this.props.navigation.navigate('signup6') },
        { text: 'Settings', onPress: () => OpenAppSettings.open() }
      ]
    );
  }

  fetchContacts() {
    Permissions.check('contacts').then(permission => {      
      if (Platform.OS === 'ios') {
        if (permission === 'restricted') return this.props.navigation.navigate('signup6');
        if (permission === 'denied') return this.createSettingsAlert();
        
        return this.getContacts();
      }

      if (Platform.OS === 'android') {
        return permission === 'restricted' ? this.createSettingsAlert() : this.requestPermissions();
      }
    });
  }
  // END: Fetch Contacts

  renderItem(contact, index) {
    const selected = this.state.selectedContacts.has(index);
    return <ContactListItem contact={contact} selected={selected} onPress={() => this.onSelectContact(index)} />;
  }

  render() {
    return (
      <View style={styles.container}>
        {/* INSTRUCTIONS */}
        <Text style={styles.instructions}>{strings('contact.importScreen_description')}</Text>

        {/* FLAT LIST OF CONTACTS */}
        <FlatList 
          ListHeaderComponent={<ListHeader isChecked={this.state.selectedContacts.size === this.state.allContacts.length} onPress={this.onSelectAll} onSkip={() => this.props.navigation.navigate('signup6')} />}
          data={this.state.allContacts}
          extraData={this.state}
          renderItem={({ item, index }) => this.renderItem(item, index)}
          keyExtractor={(item) => item.recordID}
          style={{ flex: 1, marginHorizontal: 10 }}
        />

        {/* SAVE AND CONTINUE BUTTON */}
        <Button
          onPress={this.onSaveButtonPress.bind(this)}
          title={strings('common.buttons.saveAndContinue')}
          buttonStyle={styles.buttonStyle}
          fontSize={20}
          iconRight={styles.chevronIconStyle}
        />
      </View>
    );
  }
}

const ListHeader = ({ isChecked, onPress, onSkip }) => (
  <View style={styles.headerContainer}>
    {/* CHECKBOX */}
    <CheckBox
      iconType='material'
      checkedIcon='check-box'
      uncheckedIcon='check-box-outline-blank'
      uncheckedColor={colors.darkGrey}
      checkedColor={colors.labelBlue}
      onPress={onPress}
      onIconPress={onPress}
      containerStyle={styles.checkBoxContainer}
      size={28}
      title={isChecked ? 'Deselect All' : 'Select All'}
      textStyle={styles.checkBoxTextStyle}
      checked={isChecked}
    />

    {/* SKIP BUTTON */}
    <TouchableOpacity style={{ marginRight: 15 }} onPress={onSkip}>
      <Text style={styles.skipButton}>SKIP</Text>
    </TouchableOpacity>
  </View>
);

const SCREEN_WIDTH = Dimensions.get('window').width;
const styles = {
  container: {
    flex: 1,
    backgroundColor: colors.offWhite
  },
  headerContainer: {
    flex: 1,
    justifyContent: 'space-between',
    alignItems: 'center',
    backgroundColor: colors.white,
    flexDirection: 'row',
    borderBottomColor: '#E0E3EF',
    borderBottomWidth: 2
  },
  checkBoxContainer: {
    backgroundColor: colors.white,
    borderWidth: 0
  },
  checkBoxTextStyle: {
    fontSize: 16,
    fontWeight: 'normal',
    color: colors.darkGrey
  },
  instructions: {
    left: 20,
    width: '90%',
    marginTop: 20,
    marginBottom: 30,
    fontSize: 16,
    color: colors.grey,
    textAlign: 'justify'
  },
  skipButton: {
    fontSize: 12,
    color: colors.darkGrey 
  },
  buttonStyle: {
    width: SCREEN_WIDTH * 0.9,
    marginTop: 15,
    marginBottom: 30,
    borderRadius: 5,
    backgroundColor: colors.buttonBlue
  },
  chevronIconStyle: {
    name: 'chevron-right', 
    color: colors.white,
    size: 30,
    style: { marginLeft: 0 }
  }
};
