/** Contains the base fields for event reuse **/
import _ from 'lodash';
import { ImagePicker, MapView, Permissions } from 'expo';
import React, { Component } from 'react';
import { Alert, Dimensions, FlatList, Image, Linking, Modal, Platform, SafeAreaView, ScrollView, Text, TouchableOpacity, TouchableWithoutFeedback, View } from 'react-native';
import { Button, Card, CheckBox, Divider, FormInput, Icon, ListItem, Tile } from 'react-native-elements';
import DateTimePicker from 'react-native-modal-datetime-picker';
import ModalDropdown from 'react-native-modal-dropdown';
import { connect } from 'react-redux';
import CoHostListItem from '../../components/lists/CoHostListItem';
import ExhibitorListItem from '../../components/lists/ExhibitorListItem';
import SpeakerListItem from '../../components/lists/SpeakerListItem';
import { FormMessage, FormLabel, Spacer, Spinner, TextButton } from '../common/';
import { eventFormReset, eventUpdate, fetchEventLatLong, friendsFetch, profileFetch } from '../../actions';
import colors from '../../config/colors.json';
import { strings } from '../../locales/i18n';

const SCREEN_WIDTH = Dimensions.get('window').width;
const height = SCREEN_WIDTH * 0.57; // ( 2 / 3.5 = 0.57) Business card dimensions

const profileNames = [];

let sortedFriends = [];
let checkedHosts = [];
let checkedSpeakers = [];
let checkedExhibitors = [];
let savedExhibitors = [];
let addedAgenda = [{ title: '', description: '', startTime: '', endTime: '', agendaLocation: '' }];

class EventForm extends Component {

  constructor(props) {
    super(props);
    this.state = {
      searchTerm: '',
      cameraRollStatus: '',
      isPrivate: false,
      selectedProfile: -1,
      isStartDateVisible: false,
      isEndDateVisible: false,
      isStartTimeVisible: false,
      isEndTimeVisible: false,
      isAgendaStartTimeVisible: false,
      isAgendaEndTimeVisible: false,
      agendaIndex: -1,
      isSortingFriends: true,
      checkedHosts: [],
      isCohostModalVisible: false,
      checkedSpeakers: [],
      isSpeakersModalVisible: false,
      checkedExhibitors: [],
      savedExhibitors: [],
      isExhibitorModalVisible: false,
      addedAgenda: [{ title: '', description: '', startTime: '', endTime: '', agendaLocation: '' }]
    };
    this.setCameraRollStatus();
  }

  /**
  * Component Will Mount
  **/
  componentWillMount() {
    addedAgenda = [{ title: '', description: '', startTime: '', endTime: '', agendaLocation: '' }];
    this.props.profileFetch();
    this.props.friendsFetch();
  }

  /**
  * Component Will Receive Props
  **/
  componentWillReceiveProps(nextProps) {
    // Sets the profiles for the profile select
    if (nextProps.profiles && profileNames.length === 0) {
      for (let i = 0; i < nextProps.profiles.length; i++) {
        profileNames.push(`${nextProps.profiles[i].profileName} | @${this.props.tagferId}`);
      }
    }

    // Sets the agenda
    if (this.props.isEditMode && this.props.navigation.state.params.agenda) {
      addedAgenda = this.props.navigation.state.params.agenda;
    }

    // Sorts friends for cohosts, speakers, and exhibitors
    if (this.state.isSortingFriends && nextProps.friends.length > 0) {
      nextProps.friends.sort((a, b) => this.compare(a, b));
      sortedFriends = nextProps.friends;
      this.setState({ isSortingFriends: false });
      checkedHosts = [];
      checkedSpeakers = [];
      checkedExhibitors = [];
      for (let i = 0; i < nextProps.friends.length; i++) {
        checkedHosts.push(false);
        checkedSpeakers.push(false);
        checkedExhibitors.push(false);
      }

      // Sets hosts, speakers, and exhibitors
      this.setState({ checkedHosts, checkedSpeakers, checkedExhibitors });
      for (let i = 0; i < sortedFriends.length; i++) {
        if ((this.props.isEditMode || this.props.isCoHostsMode) && this.props.navigation.state.params.coHosts) {
          for (let j = 0; j < this.props.navigation.state.params.coHosts.length; j++) {
            if (sortedFriends[i].uid === this.props.navigation.state.params.coHosts[j].uid) {
              checkedHosts[i] = true;
            }
          }
        }
        if ((this.props.isEditMode || this.props.isSpeakersMode) && this.props.navigation.state.params.speakers) {
          for (let j = 0; j < this.props.navigation.state.params.speakers.length; j++) {
            if (sortedFriends[i].uid === this.props.navigation.state.params.speakers[j].uid) {
              checkedSpeakers[i] = true;
            }
          }
        }
        if ((this.props.isEditMode || this.props.isExhibitorsMode) && this.props.navigation.state.params.exhibitors) {
          savedExhibitors = this.props.navigation.state.params.exhibitors;
          this.setState({ savedExhibitors });
        }
      }
    }
    if (nextProps.friends.length === 0) {
      this.setState({ isSortingFriends: false });
    }
  }

  /**
  * Sends user to the gallery to upload image from device
  **/
  onPickImageButtonPress = async () => {
    if (this.state.cameraRollStatus !== 'granted') {
      await Permissions.askAsync(Permissions.CAMERA_ROLL)
      .then((data) => {
        if (data.status !== 'granted') {
          Alert.alert(strings('common.error.permissionDenied_cameraRoll'));
          Linking.openURL('app-settings:');
          return;
        }
      }).catch(err => console.error('askAsync camera roll error ', err));
      this.setCameraRollStatus();
    }

    const result = await ImagePicker.launchImageLibraryAsync({
      allowsEditing: true,
      aspect: [3.5, 2],
      base64: true,
      mediaTypes: ImagePicker.MediaTypeOptions.Images
    });

    if (!result.cancelled) {
      this.props.eventUpdate({ prop: 'eventMainImg', value: result.uri });
    }
  };

  /**
  * Opens the camera for the user to take a new photo
  **/
  onTakePhotoButtonPress = async () => {
    const result = await ImagePicker.launchCameraAsync({
      allowsEditing: true,
      aspect: [4, 3],
      base64: true
    });

    if (!result.cancelled) {
      this.props.eventUpdate({ prop: 'eventMainImg', value: result.uri });
    }
  };

  /**
  * Gets the current permission state of the app for camera roll/photos
  **/
  setCameraRollStatus = async () => {
    const { status } = await Permissions.getAsync(Permissions.CAMERA_ROLL);
    this.setState({ cameraRollStatus: status });
  }

  /**
  * Opens the modal for displaying the start date
  **/
  showStartDatePicker = () => {
    this.setState({ isStartDateVisible: true });
  }

  /**
  * Opens the modal for displaying the end date
  **/
  showEndDatePicker = () => {
    this.setState({ isEndDateVisible: true });
  }

  /**
  * Opens the modal for displaying the start time
  **/
  showStartTimePicker = () => {
    this.setState({ isStartTimeVisible: true });
  }

  /**
  * Opens the modal for displaying the end time
  **/
  showEndTimePicker = () => {
    this.setState({ isEndTimeVisible: true });
  }

  /**
  * Opens the modal for displaying the agenda start time
  **/
  showAgendaStartTimePicker = () => {
    this.setState({ isAgendaStartTimeVisible: true });
  }

  /**
  * Opens the modal for displaying the agenda end time
  **/
  showAgendaEndTimePicker = () => {
    this.setState({ isAgendaEndTimeVisible: true });
  }

  /**
  * Closes the modal for displaying the start date
  **/
  hideStartDatePicker = () => {
    this.setState({ isStartDateVisible: false });
  }

  /**
  * Closes the modal for displaying the end date
  **/
  hideEndDatePicker = () => {
    this.setState({ isEndDateVisible: false });
  }

  /**
  * Closes the modal for displaying the start time
  **/
  hideStartTimePicker = () => {
    this.setState({ isStartTimeVisible: false });
  }

  /**
  * Closes the modal for displaying the end time
  **/
  hideEndTimePicker = () => {
    this.setState({ isEndTimeVisible: false });
  }

  /**
  * Closes the modal for displaying the agenda start time
  **/
  hideAgendaStartTimePicker = () => {
    this.setState({ isAgendaStartTimeVisible: false });
  }

  /**
  * Closes the modal for displaying the agenda end time
  **/
  hideAgendaEndTimePicker = () => {
    this.setState({ isAgendaEndTimeVisible: false });
  }

  /**
  * Updates redux with the proper start date
  **/
  handleStartDatePicker = (startDate) => {
    this.props.eventUpdate({ prop: 'startDate', value: new Date(startDate).toLocaleDateString() });
    this.hideStartDatePicker();
  };

  /**
  * Updates redux with the proper end date
  **/
  handleEndDatePicker = (endDate) => {
    this.props.eventUpdate({ prop: 'endDate', value: new Date(endDate).toLocaleDateString() });
    this.hideEndDatePicker();
  };

  /**
  * Updates redux with the proper start time
  **/
  handleStartTimePicker = (startTime) => {
    this.props.eventUpdate({ prop: 'startTime', value: new Date(startTime).toLocaleTimeString() });
    this.hideStartTimePicker();
  };

  /**
  * Updates redux with the proper end time
  **/
  handleEndTimePicker = (endTime) => {
    this.props.eventUpdate({ prop: 'endTime', value: new Date(endTime).toLocaleTimeString() });
    this.hideEndTimePicker();
  };

  /**
  * Updates redux with the proper agenda start time
  **/
  handleAgendaStartTimePicker = (startTime) => {
    addedAgenda[this.state.agendaIndex].startTime = new Date(startTime).toLocaleTimeString();
    this.props.eventUpdate({ prop: 'agenda', value: addedAgenda });

    this.hideAgendaStartTimePicker();
  };

  /**
  * Updates redux with the proper agenda end time
  **/
  handleAgendaEndTimePicker = (endTime) => {
    addedAgenda[this.state.agendaIndex].endTime = new Date(endTime).toLocaleTimeString();
    this.props.eventUpdate({ prop: 'agenda', value: addedAgenda });

    this.hideAgendaEndTimePicker();
  };

  /**
  * Used for sorting friends based on fullName property
  **/
  compare(a, b) {
    if (a.fullName.toLowerCase() < b.fullName.toLowerCase()) {
      return -1;
    }
    if (a.fullName.toLowerCase() > b.fullName.toLowerCase()) {
      return 1;
    }
    return 0;
  }

  /**
  * When a user clicks enter it will search for the eventLocation
  **/
  handleLocationKeyDown(e) {
    if (e.nativeEvent.key === 'Enter') {
      const term = this.state.searchTerm;
      this.props.eventUpdate({ prop: 'eventLocation', value: term });
      this.props.fetchEventLatLong({ eventLocation: term });
    }
  }

  /**
  * When a user leaves the eventLocation field it will search for the eventLocation
  **/
  handleLocationBlur() {
    const term = this.state.searchTerm;
    this.props.eventUpdate({ prop: 'eventLocation', value: term });
    this.props.fetchEventLatLong({ eventLocation: term });
  }

  /**
  * When a user clicks enter it will search for the eventAddress
  **/
  handleAddressKeyDown(e) {
    if (e.nativeEvent.key === 'Enter') {
      const term = this.state.searchTerm;
      this.props.eventUpdate({ prop: 'eventAddress', value: term });
      this.props.fetchEventLatLong({ eventAddress: term });
    }
  }

  /**
  * When a user leaves the eventAddress field it will search for the eventAddress
  **/
  handleAddressBlur() {
    const term = this.state.searchTerm;
    this.props.eventUpdate({ prop: 'eventAddress', value: term });
    this.props.fetchEventLatLong({ eventAddress: term });
  }

  /**
  * Creates a unique key for each contact
  **/
  keyExtractor = (item) => {
    return `${item.uid}`;
  }

  /**
  * Used to update the selection of a cohosts list item
  **/
  updateCohostsCheckboxes(index) {
    checkedHosts[index] = !checkedHosts[index];
    this.setState({ checkedHosts });
    const coHosts = [];

    for (let i = 0; i < checkedHosts.length; i++) {
      if (checkedHosts[i]) {
        coHosts.push(sortedFriends[i]);
      }
    }
    this.props.eventUpdate({ prop: 'coHosts', value: coHosts });
  }

  /**
  * Used to update the selection of a speakers list item
  **/
  updateSpeakersCheckboxes(index) {
    checkedSpeakers[index] = !checkedSpeakers[index];
    this.setState({ checkedSpeakers });
    const speakers = [];

    for (let i = 0; i < checkedSpeakers.length; i++) {
      if (checkedSpeakers[i]) {
        speakers.push(sortedFriends[i]);
      }
    }
    this.props.eventUpdate({ prop: 'speakers', value: speakers });
  }

  /**
  * Updates the saved exhibitors
  **/
  updateSavedExhibitors(index) {
    checkedExhibitors[index] = true;
    this.setState({ checkedExhibitors, isExhibitorModalVisible: false });

    savedExhibitors.push({ exhibitor: sortedFriends[index], aboutList: '', representatives: [{ fullName: '', companyInfo: '', tagferId: '' }] });
  }

  /**
  * Renders the mapView
  **/
  renderMapView() {
    let latitude;
    let longitude;

    if (this.props.navigation.state.params && this.props.navigation.state.params.latitude && this.props.navigation.state.params.longitude) {
      latitude = this.props.navigation.state.params.latitude;
      longitude = this.props.navigation.state.params.longitude;
    }

    if (this.props.latitude && this.props.longitude) {
      latitude = this.props.latitude;
      longitude = this.props.longitude;
    }

    if (this.props.eventLocation !== null && this.props.eventLocation.length > 0 && latitude && longitude) {
      return (
      <View style={{ width: SCREEN_WIDTH, height: SCREEN_WIDTH }}>
      <MapView
        style={{ flex: 1 }}
        region={{
          latitude,
          longitude,
          latitudeDelta: 0.0922,
          longitudeDelta: 0.0421,
        }}
      />
      </View>
      );
    }
  }

  /**
  * Render content for the create screen
  **/
  renderCreateScreenContent() {
    const hostIdx = parseInt(this.props.hostProfileIdx, 10);
    let defaultProfileValue = strings('common.modalDropDown.defaultValue');

    if (this.props.profiles && !isNaN(hostIdx)) {
      defaultProfileValue = `${this.props.profiles[hostIdx].profileName} | @${this.props.tagferId}`;
    }

    if (this.props.isEditMode || this.props.isCreateMode) {
      return (
        <View>
          <View style={{ flex: 1 }}>
            <View style={styles.imageSectionViewStyle}>
              {this.renderEventPhoto()}
              {this.renderPhotoButtons()}
            </View>
          </View>
          <Spacer />

          <View>
            <CheckBox
              title={strings('event.createScreen.privateCheckBox_label')}
              checked={this.state.isPrivate}
              containerStyle={{ backgroundColor: colors.transparent, borderWidth: 0 }}
              onPress={() => {
              const isPrivate = !this.state.isPrivate;
              this.setState({ isPrivate });
              this.props.eventUpdate({ prop: 'isPrivate', value: isPrivate });
              }}
            />

            <ModalDropdown
              style={styles.modalDropdownStyle}
              textStyle={styles.modalDropdownTextStyle}
              dropdownStyle={styles.modalDropsdownDropdownStyle}
              dropdownTextStyle={styles.modalDropsdownDropdownTextStyle}
              onSelect={(idx) => {
                this.setState({ selectedProfile: idx });
                this.props.eventUpdate({ prop: 'hostProfileIdx', value: idx });
                this.props.eventUpdate({ prop: 'hostProfile', value: this.props.profiles[idx] });
              }}
              options={profileNames}
              defaultIndex={hostIdx}
              defaultValue={defaultProfileValue}
            />
          </View>

          <FormLabel bold labelText={strings('forms.event.eventName_labelText')} />
          <FormInput
            value={this.props.eventName}
            placeholder={strings('forms.event.eventName_placeholder')}
            onChangeText={value => this.props.eventUpdate({ prop: 'eventName', value })}
            autoCorrect={false}
            autoCapitalize='none'
            inputStyle={styles.textBoxStyles}
          />
          <Spacer />

          <FormLabel bold labelText={strings('forms.event.eventDescription_labelText')} />
          <FormInput
            value={this.props.eventDescription}
            placeholder={strings('forms.event.eventDescription_labelText')}
            onChangeText={value => this.props.eventUpdate({ prop: 'eventDescription', value })}
            autoCorrect={false}
            autoCapitalize='none'
            multiline
            numberOfLines={4}
            inputStyle={styles.textBoxStyles}
          />
          <Spacer />

          <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between', marginRight: 30 }}>
            <View>
              <FormLabel bold labelText={strings('forms.event.eventDateStart_labelText')} />
              {this.renderStartDate()}
            </View>

            <View>
              <FormLabel bold labelText={strings('forms.event.eventDateEnd_labelText')} />
              {this.renderEndDate()}
            </View>
          </View>
          <Spacer />

          <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between', marginRight: 30 }}>
            <View>
              <FormLabel bold labelText={strings('forms.event.startTime_labelText')} />
              {this.renderStartTime()}
            </View>

            <View>
              <FormLabel bold labelText={strings('forms.event.endTime_labelText')} />
              {this.renderEndTime()}
            </View>
          </View>
          <Spacer />

          <FormLabel bold labelText={strings('forms.event.location_labelText')} />
          <FormInput
            placeholder={strings('forms.event.location_labelText')}
            onChangeText={value => this.setState({ searchTerm: value })}
            autoCorrect={false}
            autoCapitalize='none'
            inputStyle={styles.textBoxStyles}
            onKeyPress={this.handleLocationKeyDown.bind(this)}
            onBlur={this.handleLocationBlur.bind(this)}
          />

          <FormLabel bold labelText={strings('forms.event.address_labelText')} />
          <FormInput
            placeholder={strings('forms.event.address_placeHolderText')}
            onChangeText={value => this.setState({ searchTerm: value })}
            autoCorrect={false}
            autoCapitalize='none'
            inputStyle={styles.textBoxStyles}
            onKeyPress={this.handleAddressKeyDown.bind(this)}
            onBlur={this.handleAddressBlur.bind(this)}
          />
          <Spacer />

          {this.renderMapView()}
          <Divider style={styles.dividerStyle} />

          <FormLabel bold labelText={strings('forms.event.agenda_labelText')} />
          {this.renderAgendaSection()}

          <TextButton
            rightText={strings('common.buttons.add')}
            rightTextStyle={{ fontSize: 20, fontWeight: 'normal' }}
            containerStyle={{ marginTop: 15 }}
            onPress={() => {
              addedAgenda.push({ title: '', description: '', startTime: '', endTime: '', agendaLocation: '' });
              this.setState({ addedAgenda });
            }}
          />

          <FormMessage error={this.props.error} />

          <DateTimePicker
            isVisible={this.state.isStartDateVisible}
            onConfirm={this.handleStartDatePicker}
            onCancel={this.hideStartDatePicker}
          />
          <DateTimePicker
            isVisible={this.state.isEndDateVisible}
            onConfirm={this.handleEndDatePicker}
            onCancel={this.hideEndDatePicker}
          />
          <DateTimePicker
            isVisible={this.state.isStartTimeVisible}
            onConfirm={this.handleStartTimePicker}
            onCancel={this.hideStartTimePicker}
            mode="time"
          />
          <DateTimePicker
            isVisible={this.state.isEndTimeVisible}
            onConfirm={this.handleEndTimePicker}
            onCancel={this.hideEndTimePicker}
            mode="time"
          />
        </View>
      );
    }
  }

  /**
  * Renders the main photo for an event
  **/
  renderEventPhoto() {
    const base64 = this.props.eventMainImg;

    if (base64) {
      return (
        <Tile
          imageSrc={{ uri: base64 }}
          featured
          containerStyle={styles.tileContainerStyle}
          imageContainerStyle={styles.tileStyle}
        />
      );
    }

    return (
      <Tile
        featured
        title={strings('event.createScreen.noImage_label')}
        containerStyle={{ height }}
        imageContainerStyle={{ height, width: SCREEN_WIDTH }}
      />
    );
  }

  /**
  * Renders the photo buttons
  **/
  renderPhotoButtons() {
    return (
      <View style={styles.buttonContainerStyle}>
        <Button
          onPress={this.onPickImageButtonPress.bind(this)}
          title={strings('common.buttons.uploadImage')}
          buttonStyle={styles.halfButtonStyle}
          disabled={this.props.loading}
          icon={{ name: 'folder' }}
        />

        <Button
          onPress={this.onTakePhotoButtonPress.bind(this)}
          title={strings('common.buttons.takePhoto')}
          buttonStyle={styles.halfButtonStyle}
          disabled={this.props.loading}
          icon={{ name: 'photo-camera' }}
        />
      </View>
    );
  }

  /**
  * Renders the startDate section
  **/
  renderStartDate() {
    if (this.props.startDate) {
      return (
        <TouchableOpacity onPress={this.showStartDatePicker}>
          <FormLabel labelText={this.props.startDate} />
        </TouchableOpacity>
      );
    }
    return (
      <TouchableOpacity onPress={this.showStartDatePicker}>
        <FormLabel labelText={strings('forms.event.eventDateTime_placeholder')} />
      </TouchableOpacity>
    );
  }

  /**
  * Renders the endDate section
  **/
  renderEndDate() {
    if (this.props.endDate) {
      return (
        <TouchableOpacity onPress={this.showEndDatePicker}>
          <FormLabel labelText={this.props.endDate} />
        </TouchableOpacity>
      );
    }
    return (
      <TouchableOpacity onPress={this.showEndDatePicker}>
        <FormLabel labelText={strings('forms.event.eventDateTime_placeholder')} />
      </TouchableOpacity>
    );
  }

  /**
  * Renders the startTime section
  **/
  renderStartTime() {
    if (this.props.startTime) {
      const formattedTime = `${this.props.startTime.substr(0, 4)}${this.props.startTime.substr(7, this.props.startTime.length)}`;
      return (
        <TouchableOpacity onPress={this.showStartTimePicker}>
          <FormLabel labelText={formattedTime} />
        </TouchableOpacity>
      );
    }
    return (
      <TouchableOpacity onPress={this.showStartTimePicker}>
        <FormLabel labelText={strings('forms.event.eventDateTime_placeholder')} />
      </TouchableOpacity>
    );
  }

  /**
  * Renders the endTime section
  **/
  renderEndTime() {
    if (this.props.endTime) {
      const formattedTime = `${this.props.endTime.substr(0, 4)}${this.props.endTime.substr(7, this.props.endTime.length)}`;

      return (
        <TouchableOpacity onPress={this.showEndTimePicker}>
          <FormLabel labelText={formattedTime} />
        </TouchableOpacity>
      );
    }
    return (
      <TouchableOpacity onPress={this.showEndTimePicker}>
        <FormLabel labelText={strings('forms.event.eventDateTime_placeholder')} />
      </TouchableOpacity>
    );
  }

  /**
  * Renders the agenda section
  **/
  renderAgendaSection() {
    const agendaList = addedAgenda.map((data, index) => {
      return (
        <View key={index} style={{ marginBottom: 10 }}>
          <View style={{ flexDirection: 'row', justifyContent: 'flex-start' }}>
            <Text style={styles.representativeNumberTextStyle}>{index + 1}</Text>
            <Icon
              name='close'
              type="simple-line-icon"
              size={30}
              color={colors.red}
              onPress={() => {
                addedAgenda.splice(index, 1);
                this.setState({ addedAgenda });
                this.props.eventUpdate({ prop: 'agenda', value: addedAgenda });
              }}
            />
          </View>

          <FormLabel bold labelText={strings('forms.event.agendaTitle_labelText')} />
          <FormInput
            value={data.title}
            placeholder={strings('forms.event.agendaTitle_placeHolderText')}
            onChangeText={value => {
              addedAgenda[index].title = value;
              this.props.eventUpdate({ prop: 'agenda', value: addedAgenda });
            }}
            autoCorrect={false}
            autoCapitalize='none'
            multiline
            numberOfLines={2}
            inputStyle={styles.inputTextStyle}
          />
          <Spacer />

          <FormLabel bold labelText={strings('forms.event.agendaDescription_labelText')} />
          <FormInput
            value={data.description}
            placeholder={strings('forms.event.agendaDescription_placeHolderText')}
            onChangeText={value => {
              addedAgenda[index].description = value;
              this.props.eventUpdate({ prop: 'agenda', value: addedAgenda });
            }}
            autoCorrect={false}
            autoCapitalize='none'
            multiline
            numberOfLines={2}
            inputStyle={styles.inputTextStyle}
          />
          <Spacer />

          <FormLabel bold labelText={strings('forms.event.agendaLocation_labelText')} />
          <FormInput
            value={data.agendaLocation}
            placeholder={strings('forms.event.agendaLocation_placeHolderText')}
            onChangeText={value => {
              addedAgenda[index].agendaLocation = value;
              this.props.eventUpdate({ prop: 'agenda', value: addedAgenda });
            }}
            autoCorrect={false}
            autoCapitalize='none'
            multiline
            numberOfLines={2}
            inputStyle={styles.inputTextStyle}
          />
          <Spacer />

          <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between', marginRight: 30 }}>
            <View style={{ width: SCREEN_WIDTH / 3 }}>
              <FormLabel bold labelText={strings('forms.event.agendaStartTime_labelText')} />
              {this.renderAgendaStartTime({ data, index })}
            </View>

            <View style={{ width: SCREEN_WIDTH / 3 }}>
              <FormLabel bold labelText={strings('forms.event.agendaEndTime_labelText')} />
              {this.renderAgendaEndTime({ data, index })}
            </View>
          </View>

          <DateTimePicker
            isVisible={this.state.isAgendaStartTimeVisible}
            onConfirm={this.handleAgendaStartTimePicker}
            onCancel={this.hideAgendaStartTimePicker}
            mode="time"
          />
          <DateTimePicker
            isVisible={this.state.isAgendaEndTimeVisible}
            onConfirm={this.handleAgendaEndTimePicker}
            onCancel={this.hideAgendaEndTimePicker}
            mode="time"
          />
        </View>
      );
    });
    return agendaList;
  }

  /**
  * Renders the agenda start time field
  **/
  renderAgendaStartTime({ data, index }) {
    if (data.startTime) {
      const formattedTime = `${data.startTime.substr(0, 4)}${data.startTime.substr(7, data.startTime.length)}`;

      return (
        <TouchableOpacity
          onPress={() => {
            this.setState({ agendaIndex: index });
            this.showAgendaStartTimePicker();
          }}
        >
          <FormLabel labelText={formattedTime} />
        </TouchableOpacity>
      );
    }
    return (
      <TouchableOpacity
        onPress={() => {
          this.setState({ agendaIndex: index });
          this.showAgendaStartTimePicker();
        }}
      >
        <FormLabel labelText={strings('forms.event.eventDateTime_placeholder')} />
      </TouchableOpacity>
    );
  }

  /**
  * Renders the agenda end time field
  **/
  renderAgendaEndTime({ data, index }) {
    if (data.endTime) {
      const formattedTime = `${data.endTime.substr(0, 4)}${data.endTime.substr(7, data.endTime.length)}`;

      return (
        <TouchableOpacity
          onPress={() => {
            this.setState({ agendaIndex: index });
            this.showAgendaEndTimePicker();
          }}
        >
          <FormLabel labelText={formattedTime} />
        </TouchableOpacity>
      );
    }
    return (
      <TouchableOpacity
        onPress={() => {
          this.setState({ agendaIndex: index });
          this.showAgendaEndTimePicker();
        }}
      >
        <FormLabel labelText={strings('forms.event.eventDateTime_placeholder')} />
      </TouchableOpacity>
    );
  }

  /**
  * Render the content for the cohosts screen
  **/
  renderCoHostsScreenContent() {
    if (this.props.isCoHostsMode) {
      return (
        <ScrollView
          contentContainerStyle={{ flexGrow: 1, backgroundColor: colors.white }}
          keyboardShouldPersistTaps="handled"
        >
          <FlatList
            keyExtractor={this.keyExtractor}
            renderItem={this.renderCoHostsFriendsListItem}
            data={sortedFriends}
            extraData={this.state}
          />
        </ScrollView>
      );
    }
    if (this.props.isEditMode) {
      return (
        <ScrollView
          contentContainerStyle={{ flexGrow: 1, backgroundColor: colors.white }}
          keyboardShouldPersistTaps="handled"
        >
          <Text style={styles.sectionLabelStyle}>{strings('event.editScreen.coHostsSection_label')}</Text>
          {this.renderAddedCoHosts()}

          <Button
            title={strings('event.editScreen.addCoHosts_button')}
            onPress={() => this.setState({ isCohostModalVisible: true })}
            backgroundColor={colors.transparent}
            color={colors.buttonBlue}
          />

          <Modal
            transparent
            animationType="slide"
            visible={this.state.isCohostModalVisible}
            onRequestClose={() => {}}
          >
            <SafeAreaView style={{ flex: 1, backgroundColor: colors.white }}>
              <TouchableOpacity
                style={styles.modalOpacityStyle}
                activeOpacity={1}
                onPressOut={() => this.setState({ isCohostModalVisible: false })}
              >
                <ScrollView
                  directionalLockEnabled
                  centerContent
                  contentContainerStyle={styles.modalScrollViewStyle}
                >
                  <TouchableWithoutFeedback>
                    <View style={styles.modalContainerStyle}>
                      <Card containerStyle={styles.modalCardStyle}>
                        <ScrollView
                          contentContainerStyle={{ flexGrow: 1, backgroundColor: colors.white }}
                          keyboardShouldPersistTaps="handled"
                        >
                          <Text style={styles.selectTextPromptStyle}>{strings('event.addCoHostsScreen.selectCoHost_label')}</Text>
                          <FlatList
                            keyExtractor={this.keyExtractor}
                            renderItem={this.renderCoHostsFriendsListItem}
                            data={sortedFriends}
                            extraData={this.state}
                          />
                          <Spacer space={60} />
                        </ScrollView>
                      </Card>
                    </View>
                  </TouchableWithoutFeedback>
                </ScrollView>
                <Button
                  title={strings('common.buttons.done')}
                  onPress={() => this.setState({ isCohostModalVisible: false })}
                  buttonStyle={styles.buttonStyle}
                  fontWeight="bold"
                  fontSize={25}
                />
              </TouchableOpacity>
            </SafeAreaView>
          </Modal>
        </ScrollView>
      );
    }
  }

  /**
  * Renders each row of the co-hosts list
  **/
  renderCoHostsFriendsListItem = ({ item, index }) => {
    return (
      <CoHostListItem
        {...this.props}
        item={item}
        index={index}
        isChecked={this.state.checkedHosts[index]}
        onPress={() => this.updateCohostsCheckboxes(index)}
      />
    );
  }

  /**
  * Renders each selected cohost
  **/
  renderAddedCoHosts = () => {
    return checkedHosts.map((thisHost, index) => {
      if (thisHost) {
        const item = sortedFriends[index];
        return (
          <View key={item.uid}>
            {this.renderCoHostsFriendsListItem({ item, index })}
          </View>
        );
      }
      return null;
    });
  }

  /**
  * Render the content for the speakers screen
  **/
  renderSpeakersScreenContent() {
    if (this.props.isSpeakersMode) {
      return (
        <ScrollView
          contentContainerStyle={{ flexGrow: 1, backgroundColor: colors.white }}
          keyboardShouldPersistTaps="handled"
        >
          <FlatList
            keyExtractor={this.keyExtractor}
            renderItem={this.renderSpeakerListItem}
            data={sortedFriends}
            extraData={this.state}
          />
        </ScrollView>
      );
    }
    if (this.props.isEditMode) {
      return (
        <ScrollView
          contentContainerStyle={{ flexGrow: 1, backgroundColor: colors.white }}
          keyboardShouldPersistTaps="handled"
        >
          <Text style={styles.sectionLabelStyle}>{strings('event.editScreen.speakersSection_label')}</Text>
          {this.renderAddedSpeakers()}

          <Button
            title={strings('event.editScreen.addSpeaker_button')}
            onPress={() => this.setState({ isSpeakersModalVisible: true })}
            backgroundColor={colors.transparent}
            color={colors.buttonBlue}
          />

          <Modal
            transparent
            animationType="slide"
            visible={this.state.isSpeakersModalVisible}
            onRequestClose={() => {}}
          >
            <SafeAreaView style={{ flex: 1, backgroundColor: colors.white }}>
              <TouchableOpacity
                style={styles.modalOpacityStyle}
                activeOpacity={1}
                onPressOut={() => this.setState({ isSpeakersModalVisible: false })}
              >
                <ScrollView
                  directionalLockEnabled
                  centerContent
                  contentContainerStyle={styles.modalScrollViewStyle}
                >
                  <TouchableWithoutFeedback>
                    <View style={styles.modalContainerStyle}>
                      <Card containerStyle={styles.modalCardStyle}>
                        <ScrollView
                          contentContainerStyle={{ flexGrow: 1, backgroundColor: colors.white }}
                          keyboardShouldPersistTaps="handled"
                        >
                          <Text style={styles.selectTextPromptStyle}>{strings('event.addSpeakersScreen.selectSpeaker_label')}</Text>
                          <FlatList
                            keyExtractor={this.keyExtractor}
                            renderItem={this.renderSpeakerListItem}
                            data={sortedFriends}
                            extraData={this.state}
                          />
                          <Spacer space={60} />
                        </ScrollView>
                      </Card>
                    </View>
                  </TouchableWithoutFeedback>
                </ScrollView>

                <Button
                  title={strings('common.buttons.done')}
                  onPress={() => this.setState({ isSpeakersModalVisible: false })}
                  buttonStyle={styles.buttonStyle}
                  fontWeight="bold"
                  fontSize={25}
                />
              </TouchableOpacity>
            </SafeAreaView>
          </Modal>
        </ScrollView>
      );
    }
  }

  /**
  * Renders each row of the speakers list
  **/
  renderSpeakerListItem = ({ item, index }) => {
    return (
      <SpeakerListItem
        {...this.props}
        item={item}
        isChecked={this.state.checkedSpeakers[index]}
        hasCheckBox
        onPress={() => this.updateSpeakersCheckboxes(index)}
      />
    );
  }

  /**
  * Renders each selected speaker
  **/
  renderAddedSpeakers = () => {
    return checkedSpeakers.map((thisSpeaker, index) => {
      if (thisSpeaker) {
        const item = sortedFriends[index];
        return (
          <View key={item.uid}>
            {this.renderSpeakerListItem({ item, index })}
          </View>
        );
      }
      return null;
    });
  }

  /**
  * Render the content for the exhibitors screen
  **/
  renderExhibitorsScreenContent() {
    if (this.props.isEditMode || this.props.isExhibitorsMode) {
      return (
        <ScrollView
          contentContainerStyle={{ flexGrow: 1, backgroundColor: colors.white }}
          keyboardShouldPersistTaps="handled"
        >
          <Text style={styles.sectionLabelStyle}>{strings('event.editScreen.exhibitorsSection_label')}</Text>
          {this.renderExhibitors()}
          {this.renderDivider()}

          <Button
            title={strings('event.addExhibitorsScreen.addExhibitor_button')}
            onPress={() => this.setState({ isExhibitorModalVisible: true })}
            buttonStyle={styles.addExhibitorsButtonStyle}
            fontWeight="bold"
            fontSize={25}
            color={colors.green}
          />

          <Modal
            transparent
            animationType="slide"
            visible={this.state.isExhibitorModalVisible}
            onRequestClose={() => {}}
          >
            <SafeAreaView style={{ flex: 1, backgroundColor: colors.white }}>
              <TouchableOpacity
                style={styles.modalOpacityStyle}
                activeOpacity={1}
                onPressOut={() => this.setState({ isExhibitorModalVisible: false })}
              >
                <ScrollView
                  directionalLockEnabled
                  centerContent
                  contentContainerStyle={styles.modalScrollViewStyle}
                >
                  <TouchableWithoutFeedback>
                    <View style={styles.modalContainerStyle}>
                      <Card containerStyle={styles.modalCardStyle}>
                        <ScrollView
                          contentContainerStyle={{ flexGrow: 1, backgroundColor: colors.white }}
                          keyboardShouldPersistTaps="handled"
                        >
                          <Text style={styles.selectTextPromptStyle}>{strings('event.addExhibitorsScreen.selectExhibitor_label')}</Text>
                          <FlatList
                            keyExtractor={this.keyExtractor}
                            renderItem={this.renderExhibitorsFriendsListItem}
                            data={sortedFriends}
                            extraData={this.state}
                          />
                          <Spacer space={60} />
                        </ScrollView>
                      </Card>
                    </View>
                  </TouchableWithoutFeedback>
                </ScrollView>

                <Button
                  title={strings('common.buttons.done')}
                  onPress={() => this.setState({ isExhibitorModalVisible: false })}
                  buttonStyle={styles.buttonStyle}
                  fontWeight="bold"
                  fontSize={25}
                />
              </TouchableOpacity>
            </SafeAreaView>
          </Modal>
        </ScrollView>
      );
    }
  }

  /**
  * Renders each row of the list
  **/
  renderExhibitorsFriendsListItem = ({ item, index }) => {
    return (
      <ExhibitorListItem
        {...this.props}
        item={item}
        onPress={() => this.updateSavedExhibitors(index)}
      />
    );
  }

  /**
  * Renders each saved exhibitor
  **/
  renderExhibitors() {
    return savedExhibitors.map((thisExhibitor, index) => {
      if (thisExhibitor) {
        const item = thisExhibitor.exhibitor;

        return (
          <View key={item.uid}>
            {this.renderExhibitorListItem({ item, index })}
            {this.renderAboutSection(index)}
            {this.renderRepresentativesSection(index)}
            <Button
              title={strings('event.addExhibitorsScreen.addRepresentative_button')}
              onPress={() => {
                savedExhibitors[index].representatives.push({ fullName: '', companyInfo: '', tagferId: '' });
                this.setState({ representatives: savedExhibitors[index].representatives });
              }}
              backgroundColor={colors.transparent}
              color={colors.buttonBlue}
            />
          </View>
        );
      }
      return null;
    });
  }

  /**
  * Renders the ListItem for the exhibitor
  **/
  renderExhibitorListItem({ item, index }) {
    const title = `@${item.tagferId}`;
    const subTitle = (
      <View>
        <Text>{item.fullName || ''}</Text>
        <Text>{item.titleAndCompany || ''}</Text>
      </View>
    );

    if (item.profileAvatarImg) {
      return (
        <View>
          <ListItem
            roundAvatar
            key={item.uid}
            title={title}
            subtitle={subTitle}
            titleStyle={{ fontWeight: 'bold', marginBottom: 5, color: colors.darkGreen }}
            containerStyle={{ borderWidth: 0, borderColor: 'transparent', borderBottomWidth: 0 }}
            leftIcon={this.renderBigAvatar({ item })}
            rightIcon={
              <Icon
                name='close'
                type="simple-line-icon"
                size={50}
                color={colors.greyBlue}
                onPress={() => {
                  savedExhibitors.splice(index, 1);
                  this.setState({ savedExhibitors });
                  this.props.eventUpdate({ prop: 'exhibitors', value: savedExhibitors });
                }}
              />
            }
          />
        </View>
      );
    }

    return (
      <View>
        <ListItem
          roundAvatar
          key={item.key}
          title={title}
          subtitle={subTitle}
          titleStyle={{ fontWeight: 'bold', marginBottom: 5, color: colors.darkGreen }}
          containerStyle={{ borderWidth: 0, borderColor: 'transparent', borderBottomWidth: 0 }}
          leftIcon={{ name: 'account-circle', size: 70, color: colors.lightGrey }}
          rightIcon={
            <Icon
              name='close'
              type="simple-line-icon"
              size={50}
              color={colors.greyBlue}
              onPress={() => {
                savedExhibitors.splice(index, 1);
                this.setState({ savedExhibitors });
                this.props.eventUpdate({ prop: 'exhibitors', value: savedExhibitors });
              }}
            />
          }
        />
      </View>
    );
  }

  /**
  * Renders the about section for that exhibitor
  **/
  renderAboutSection(index) {
    return (
      <View>
        <Spacer />
        <FormLabel bold labelText={strings('common.contactFields.about_labelText')} />
        <FormInput
          value={savedExhibitors[index].aboutList}
          placeholder={strings('event.addExhibitorsScreen.about_placeholder')}
          onChangeText={value => {
            savedExhibitors[index].aboutList = value;
            this.props.eventUpdate({ prop: 'exhibitors', value: savedExhibitors });
          }}
          autoCorrect={false}
          autoCapitalize='none'
          multiline
          numberOfLines={4}
          inputStyle={styles.textBoxStyles}
        />
      </View>
    );
  }

  /**
  * Renders the representatives section
  **/
  renderRepresentativesSection(index) {
    if (savedExhibitors[index].representatives.length === 0) {
      return;
    }

    const representativeArray = savedExhibitors[index].representatives.map((thisRepresentative, repIndex) => {
      return (
        <View key={`${index}a${repIndex}b`}>
          <Spacer />
          <FormLabel bold labelText={strings('event.addExhibitorsScreen.representatives_labelText')} />
          <View style={{ flexDirection: 'row', justifyContent: 'flex-start' }}>
            <Text style={styles.representativeNumberTextStyle}>{repIndex + 1}</Text>
            <Icon
              name='close'
              type="simple-line-icon"
              size={30}
              color={colors.red}
              onPress={() => {
                savedExhibitors[index].representatives.splice(repIndex, 1);
                this.setState({ savedExhibitors });
                this.props.eventUpdate({ prop: 'exhibitors', value: savedExhibitors });
              }}
            />
          </View>
          <Spacer />

          <FormInput
            value={savedExhibitors[index].representatives[repIndex].fullName}
            placeholder={strings('event.addExhibitorsScreen.representativesFullName_labelText')}
            onChangeText={value => {
              savedExhibitors[index].representatives[repIndex].fullName = value;
              this.props.eventUpdate({ prop: 'exhibitors', value: savedExhibitors });
            }}
            autoCorrect={false}
            autoCapitalize='none'
            inputStyle={styles.inputTextStyle}
          />
          <Spacer />

          <FormInput
            value={savedExhibitors[index].representatives[repIndex].companyInfo}
            placeholder={strings('event.addExhibitorsScreen.representativesCompanyInfo_labelText')}
            onChangeText={value => {
              savedExhibitors[index].representatives[repIndex].companyInfo = value;
              this.props.eventUpdate({ prop: 'exhibitors', value: savedExhibitors });
            }}
            autoCorrect={false}
            autoCapitalize='none'
            inputStyle={styles.inputTextStyle}
          />
          <Spacer />

          <FormInput
            value={savedExhibitors[index].representatives[repIndex].tagferId}
            placeholder={strings('event.addExhibitorsScreen.representativesTagferID_labelText')}
            onChangeText={value => {
              savedExhibitors[index].representatives[repIndex].tagferId = value;
              this.props.eventUpdate({ prop: 'exhibitors', value: savedExhibitors });
            }}
            autoCorrect={false}
            autoCapitalize='none'
            inputStyle={styles.inputTextStyle}
          />
          <Spacer />
        </View>
      );
    });

    return representativeArray;
  }

  /**
  * Shows a divider if exhibitors have been added
  **/
  renderDivider() {
    if (savedExhibitors.length > 0) {
      return (
        <View>
          <Spacer />
          <Divider style={styles.dividerStyle} />
          <Spacer />
        </View>
      );
    }
  }

  /**
  * Creates the big contact avatar
  **/
  renderBigAvatar({ item }) {
    return (
      <Image
        source={{ uri: item.profileAvatarImg }}
        style={styles.bigAvatarImageStyle}
      />
    );
  }

  /**
  * Render method
  **/
  render() {
    if (this.state.isSortingFriends) {
      return (
        <View style={{ flex: 1, backgroundColor: colors.white }}>
          <Spinner size="large" />
        </View>
      );
    }

    return (
      <View>
        <Spacer />
        {this.renderCreateScreenContent()}
        {this.renderCoHostsScreenContent()}
        {this.renderSpeakersScreenContent()}
        {this.renderExhibitorsScreenContent()}
        <Spacer />

      </View>
    );
  }
}

const styles = {
  imageSectionViewStyle: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center'
  },
  buttonContainerStyle: {
    flex: 2,
    marginTop: 15,
    flexDirection: 'row',
    justifyContent: 'center'
  },
  halfButtonStyle: {
    backgroundColor: colors.buttonBlue,
    flex: 1,
    borderRadius: 5
  },
  modalDropdownStyle: {
    alignSelf: 'center',
    width: SCREEN_WIDTH * 0.9,
    marginLeft: 20,
    right: 8,
    borderBottomWidth: 1
  },
  modalDropdownTextStyle: {
    marginVertical: 10,
    marginLeft: 10,
    fontSize: 18,
    color: colors.black
  },
  modalDropsdownDropdownStyle: {
    width: SCREEN_WIDTH * 0.9,
    borderColor: colors.lightgrey,
    borderWidth: 1
  },
  modalDropsdownDropdownTextStyle: {
    fontSize: 18
  },
  buttonStyle: {
    position: 'absolute',
    bottom: 0,
    width: '100%',
    marginVertical: 15,
    backgroundColor: colors.buttonBlue
  },
  textBoxStyles: {
    flex: 1,
    width: '100%',
    borderBottomWidth: Platform.OS === 'android' ? 1 : 0,
    borderColor: colors.middleGrey,
    color: colors.black
  },
  inputTextStyle: {
    width: '100%',
    color: colors.black
  },
  agendaTimeInputStyle: {
    width: '100%',
    color: colors.black
  },
  bigAvatarImageStyle: {
    width: 60,
    height: 60,
    borderWidth: 1,
    borderRadius: 30,
    marginLeft: 5,
    marginRight: 10
  },
  sectionLabelStyle: {
    fontSize: 30,
    fontWeight: 'bold',
    alignSelf: 'center',
    marginBottom: 15
  },
  representativeNumberTextStyle: {
    color: colors.orange,
    fontSize: 15,
    fontWeight: 'bold',
    marginHorizontal: 20,
    alignSelf: 'center'
  },
  deleteButtonStyle: {
    borderWidth: 1,
    borderRadius: 5,
    backgroundColor: colors.white,
    borderColor: colors.buttonBlue
  },
  dividerStyle: {
    backgroundColor: colors.middleGrey,
    marginTop: 10,
    marginBottom: 15
  },
  addExhibitorsButtonStyle: {
    width: SCREEN_WIDTH * 0.9,
    marginTop: 15,
    marginBottom: 30,
    borderRadius: 5,
    borderWidth: 2,
    backgroundColor: colors.transparent,
    borderColor: colors.green
  },
  modalOpacityStyle: {
    backgroundColor: colors.modalTransparency,
    position: 'relative',
    flex: 1,
    justifyContent: 'center'
  },
  modalScrollViewStyle: {
    backgroundColor: colors.white,
  },
  modalContainerStyle: {
    backgroundColor: colors.modalTransparency,
    position: 'relative',
    flex: 1,
    justifyContent: 'center'
  },
  modalCardStyle: {
    justifyContent: 'center'
  }
};

// If you add any items here be sure to update the lists in
// EventEditScreen, EventCreateScreen, EventActions, and EventFormReducer
const mapStateToProps = (state) => {
  // converts Profile objects into profile arrays
  const profiles = _.map(state.profiles, (val, uid) => {
      return { ...val, uid };
  });

  //converts friend object of objects into friend array of objects
  const friends = _.map(state.friends, (val, uid) => {
    return { ...val, uid };
  });

  const { tagferId } = state.properties;

  const {
    agenda,
    endDate,
    eventAddress,
    eventDescription,
    eventLocation,
    eventMainImg,
    eventName,
    endTime,
    isPrivate,
    hostProfile,
    hostProfileIdx,
    hostUid,
    latitude,
    longitude,
    startDate,
    startTime,
    coHosts,
    speakers,
    exhibitors,
    eventUid,
    error
  } = state.eventForm;

  return {
    profiles,
    friends,
    tagferId,
    agenda,
    endDate,
    eventAddress,
    eventDescription,
    eventLocation,
    eventMainImg,
    eventName,
    endTime,
    isPrivate,
    hostProfile,
    hostProfileIdx,
    hostUid,
    latitude,
    longitude,
    startDate,
    startTime,
    coHosts,
    speakers,
    exhibitors,
    eventUid,
    error
  };
};

export default connect(mapStateToProps, {
  eventFormReset, eventUpdate, fetchEventLatLong, friendsFetch, profileFetch
})(EventForm);
