/** Contains the base fields for Profile reuse **/
import { AuthSession } from 'expo';
import React, { Component } from 'react';
import { Alert, Animated, Dimensions, ScrollView, Text, View } from 'react-native';
import { Button, Card, CheckBox, Divider, FormInput, Icon } from 'react-native-elements';
import { connect } from 'react-redux';
import { profileUpdate, propertyUpdate } from '../../actions';
import ProfileAvatar from '../ProfileAvatar';
import BizCard from '../BizCard';
import { Confirm, FormLabel, FormMessage, Keyword, Spacer, TextButton } from '../common';
import { PROFILE_FORM } from '../FormTypes';
import colors from '../../config/colors.json';
import privateKeys from '../../../private_keys.json';
import { strings } from '../../locales/i18n';

const SCREEN_WIDTH = Dimensions.get('window').width;
const DOTS_SIZE = ['first', 'second'];
const scrollX = new Animated.Value(0);

let addedExperience = [{ jobTitle: '', jobCompany: '', jobDates: '', jobLocation: '', jobSummary: '' }];
let addedEducation = [{ school: '', degree: '', fieldOfStudy: '', schoolDates: '', educationSummary: '' }];

/**
* Converts an object to a query string.
*/
function toQueryString(params) {
  return '?' + Object.entries(params)
    .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
    .join('&');
}

class ProfileForm extends Component {
  state = {
    keyword: '',
    keywords: [],
    isVisible: false,
    addedExperience: [{ jobTitle: '', jobCompany: '', jobDates: '', jobLocation: '', jobSummary: '' }],
    addedEducation: [{ school: '', degree: '', fieldOfStudy: '', schoolDates: '', educationSummary: '' }]
  };

  /**
  * Component Will Mount
  **/
  componentWillMount() {
    addedExperience = [{ jobTitle: '', jobCompany: '', jobDates: '', jobLocation: '', jobSummary: '' }];
    addedEducation = [{ school: '', degree: '', fieldOfStudy: '', schoolDates: '', educationSummary: '' }];

    if (this.props.experience) {
      addedExperience = this.props.experience;
    }
    if (this.props.education) {
      addedEducation = this.props.education;
    }
    if (this.props.isEditMode) {
      const newKeywordsArr = [];
      for (let i = 0; i < this.props.keywords.length; i++) {
          newKeywordsArr.push(this.props.keywords[i]);
      }
      this.setState({ keywords: newKeywordsArr });
    }
  }

  /**
  * Component Will Receive Props
  **/
  componentWillReceiveProps(nextProps) {
    if (nextProps.keywords) {
      const newKeywordsArr = [];
      for (let i = 0; i < nextProps.keywords.length; i++) {
          newKeywordsArr.push(nextProps.keywords[i]);
      }
      this.setState({ keywords: newKeywordsArr });
    }
  }

  /**
  * Closes the description modal
  **/
  onOkay() {
    this.setState({ isVisible: false });
  }

  /**
  * Adds a keyword when the add button is pressed
  **/
  onAddKeywordPress() {
    if (this.state.keyword.trim() === '') {
      return;
    }
    if (this.state.keywords.length >= 8) {
      return;
    }
    const newKeywordsArr = [];
    for (let i = 0; i < this.state.keywords.length; i++) {
        newKeywordsArr.push(this.state.keywords[i]);
    }
    if (this.state.keyword.indexOf(',') >= 0) {
      let keywordsToAddArr = [];
      keywordsToAddArr = this.state.keyword.split(',');
      for (let i = 0; i < keywordsToAddArr.length; i++) {
        if (keywordsToAddArr[i] !== '') {
          newKeywordsArr.push(keywordsToAddArr[i].trim());
        }
      }
    } else {
      newKeywordsArr.push(this.state.keyword.trim());
    }
    while (newKeywordsArr.length > 8) {
      newKeywordsArr.pop();
    }
    this.setState({ keywords: newKeywordsArr, keyword: '' });
    this.props.profileUpdate({ prop: 'keywords', value: newKeywordsArr });
  }

  /**
  * Opens a webview for the user to login to LinkedIn
  **/
  loginWithAuth0LinkedIn = async () => {
    const redirectUrl = AuthSession.getRedirectUrl();

    const result = await AuthSession.startAsync({
      authUrl: `${privateKeys.auth0.domain}/authorize` + toQueryString({
        connection: 'linkedin',
        client_id: privateKeys.auth0.clientId,
        response_type: 'token',
        scope: 'openid profile',
        audience: 'https://tagfer.com/gettwitteruser', //TODO CREATE AN APP FOR LINKEDIN
        redirect_uri: redirectUrl
      }),
    });

    if (result.type === 'success') {
      this.handleParams(result.params);
    }
  }

  /**
  * Uses the login response to get the LinkedIn data
  **/
  handleParams = async (responseObj) => {
    if (responseObj.error) {
      Alert.alert('Error', responseObj.error_description || strings('common.error.loginFailed'));
      return;
    }
    let nickname = '';
    const userInfo = await fetch(`${privateKeys.auth0.domain}/userinfo?access_token=${responseObj.access_token}`);
    if (userInfo.status === 200) {
      const parsedUserInfo = await userInfo.json();
      nickname = parsedUserInfo.nickname;
    } else {
      console.log('Something went wrong. ErrorCode: ', userInfo.status);
    }
    nickname = nickname.replace(/"/g, '');
    nickname = nickname.replace(/ /g, '+');

    const userSearchResponse = await fetch(`${privateKeys.auth0.domain}/api/v2/users?q=nickname%3A%22${nickname}%22'`, {
      method: 'GET',
      headers: {
        authorization: `Bearer ${privateKeys.auth0.managementToken}`
      }
    });

    const userSearchParsed = await userSearchResponse.json();

    this.extractLinkedInData(userSearchParsed);
  }

  /**
  * The search brings back an array and we need to find the user's LinkedIn data
  **/
  extractLinkedInData(userDataArr) {
    for (let i = 0; i < userDataArr.length; i++) {
      const userId = userDataArr[i].user_id;
      const linkedInIndex = userId.indexOf('linkedin');

      if (linkedInIndex === 0) {
        this.props.profileUpdate({ prop: 'headline', value: userDataArr[i].headline || userDataArr[i].summary });
        this.props.profileUpdate({ prop: 'location', value: userDataArr[i].location.name });

        // refactored in https://github.com/Tagfer/tagfer-native/issues/1174
        for (let j = 0; j < userDataArr[i].positions.values.length; j++) {
          addedExperience[j].jobTitle = userDataArr[i].positions.values[j].title;
          addedExperience[j].jobCompany = userDataArr[i].positions.values[j].company.name;
          addedExperience[j].jobDates = `${userDataArr[i].positions.values[0].startDate.month}/${userDataArr[i].positions.values[0].startDate.year}`;
          addedExperience[j].jobLocation = userDataArr[i].positions.values[j].location.name;
          addedExperience[j].jobSummary = userDataArr[i].positions.values[j].jobSummary;
        }
        //TODO ADD IN THE EDUCATION INFORMATION FROM LINKEDIN
      }
    }
  }

  /**
  * Handles removal of a keyword when the X is clicked
  **/
  removeKeyword(index) {
    const newKeywordsArr = [];
    for (let i = 0; i < this.state.keywords.length; i++) {
        newKeywordsArr.push(this.state.keywords[i]);
    }
    newKeywordsArr.splice(index, 1);
    this.setState({ keywords: newKeywordsArr });
    this.props.profileUpdate({ prop: 'keywords', value: newKeywordsArr });
  }

  /**
  * Breaks the fullName into a first and last name for profile saving
  **/
  splitNameField(value) {
    this.props.profileUpdate({ prop: 'fullName', value });

    const nameArr = this.props.fullName.split(' ');
    const firstName = nameArr[0];
    this.props.profileUpdate({ prop: 'firstName', value: firstName });

    if (nameArr.length > 0) {
      const lastName = nameArr[1];
      this.props.profileUpdate({ prop: 'lastName', value: lastName });
    }
  }

  /**
  * Renders the avatar and biz card slider
  **/
  renderAvatarBizCardSlider() {
    const position = Animated.divide(scrollX, SCREEN_WIDTH);

    // Edit mode has the details form below the avatar
    if (this.props.isEditMode) {
      return (
        <View style={{ backgroundColor: colors.white }}>
          <ScrollView
            horizontal
            pagingEnabled
            showsHorizontalScrollIndicator={false}
            onScroll={Animated.event(
              [{ nativeEvent: { contentOffset: { x: scrollX } } }]
            )}
            scrollEventThrottle={16}
          >
            <View style={styles.slideStyle}>
              <View style={{ flex: 1, justifyContent: 'center' }}>
                <ProfileAvatar
                  {...this.props}
                  formType={PROFILE_FORM}
                  isEditMode={this.props.isEditMode}
                />
              </View>
            </View>

            <View style={styles.slideStyle}>
              <BizCard
                formType={PROFILE_FORM}
                isEditMode={this.props.isEditMode}
              />
            </View>
          </ScrollView>

          <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'center' }}>
            {DOTS_SIZE.map((_, i) => {
              const opacity = position.interpolate({
                inputRange: [i - 1, i, i + 1],
                outputRange: [0.3, 1, 0.3],
                extrapolate: 'clamp'
              });

              return (
                <Animated.View
                  key={i}
                  style={{ opacity, height: 10, width: 10, backgroundColor: '#595959', margin: 8, borderRadius: 5 }}
                />
              );
            })}

          </View>
          {this.renderDetailsSection()}
        </View>
      );
    }

    // NORMAL MODE - Details section with the avatar
    return (
      <View style={styles.detailsSectionStyle}>
        <ScrollView
          horizontal
          pagingEnabled
          showsHorizontalScrollIndicator={false}
          onScroll={Animated.event(
            [{ nativeEvent: { contentOffset: { x: scrollX } } }]
          )}
          scrollEventThrottle={16}
        >
          <View style={styles.slideStyle}>
            <ProfileAvatar
              {...this.props}
              formType={PROFILE_FORM}
              isEditMode={this.props.isEditMode}
            />
            {this.renderDetailsSection()}
          </View>

          <View style={styles.slideStyle}>
            <BizCard
              formType={PROFILE_FORM}
              isEditMode={this.props.isEditMode}
            />
          </View>
        </ScrollView>

        <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'center' }}>
          {DOTS_SIZE.map((_, i) => {
            const opacity = position.interpolate({
              inputRange: [i - 1, i, i + 1],
              outputRange: [0.3, 1, 0.3],
              extrapolate: 'clamp'
            });

            return (
              <Animated.View
                key={i}
                style={{ opacity, height: 10, width: 10, backgroundColor: '#595959', margin: 8, borderRadius: 5 }}
              />
            );
          })}

        </View>
      </View>
    );
  }

  /**
  * Renders the top section under the avatar
  **/
  renderDetailsSection() {
    if (this.props.isEditMode) {
      return (
        <View>
          <Divider style={styles.dividerStyle} />

          <Spacer />
          <TextButton
            rightText={strings('common.contactFields.linkedIn_import')}
            rightTextStyle={{ fontSize: 20, fontWeight: 'normal' }}
            containerStyle={{ marginLeft: -2, marginTop: 15 }}
            onPress={() => this.loginWithAuth0LinkedIn()}
          />

          <FormLabel bold labelText={strings('common.contactFields.fullName_labelText')} />
          <FormInput
            value={this.props.fullName}
            placeholder={strings('common.contactFields.fullName_placeholder')}
            onChangeText={value => this.splitNameField(value)}
            autoCorrect={false}
            autoCapitalize='none'
            inputStyle={styles.inputTextStyle}
          />

          <Spacer />
          <FormLabel bold labelText={strings('common.contactFields.headline_labelText')} />
          <FormInput
            value={this.props.headline}
            placeholder={strings('common.contactFields.headline_placeholder')}
            onChangeText={value => this.props.profileUpdate({ prop: 'headline', value })}
            autoCorrect={false}
            autoCapitalize='none'
            multiline
            numberOfLines={4}
            inputStyle={styles.inputTextStyle}
          />

          <Spacer />
          <FormLabel required bold labelText={strings('common.contactFields.titleAndCompany_labelText')} />
          <FormInput
            value={this.props.titleAndCompany}
            placeholder={strings('common.contactFields.titleAndCompany_placeholder')}
            onChangeText={value => this.props.profileUpdate({ prop: 'titleAndCompany', value })}
            autoCorrect={false}
            autoCapitalize='none'
            inputStyle={styles.inputTextStyle}
          />

          <Spacer />
          <FormLabel bold labelText={strings('common.contactFields.location_labelText')} />
          <FormInput
            value={this.props.location}
            placeholder={strings('common.contactFields.location_placeholder')}
            onChangeText={value => this.props.profileUpdate({ prop: 'location', value })}
            autoCorrect={false}
            autoCapitalize='none'
            inputStyle={styles.inputTextStyle}
          />
        </View>
      );
    }

    // NORMAL - VIEW MODE
    return (
      <View style={{ flex: 1, flexDirection: 'column', alignItems: 'center', marginLeft: -10 }}>
        <FormLabel bold labelText={`@${this.props.tagferId}`} textStyle={{ color: colors.darkGreen, fontSize: 18 }} />
        <FormLabel bold labelText={this.props.fullName} textStyle={{ fontSize: 22, marginHorizontal: 20, color: colors.darkGrey }} />
        <FormLabel bold labelText={this.props.headline} textStyle={{ fontSize: 15, marginHorizontal: 20, color: colors.labelBlue }} />
        <FormLabel bold labelText={this.props.titleAndCompany} textStyle={{ fontSize: 15, marginHorizontal: 20 }} />
        <FormLabel bold labelText={this.props.location} textStyle={{ fontSize: 15, marginHorizontal: 20, color: colors.middleGrey }} />
      </View>
    );
  }

  /**
  * Renders the profile name section
  **/
  renderProfileNameSection() {
    if (this.props.isCreateMode) {
      return (
        <View>
          <View style={styles.checkboxRowStyle}>
            <Icon
              name={'help-outline'}
              containerStyle={styles.helpIconStyle}
              onPress={() => this.setState({ isVisible: true })}
            />
            <FormLabel bold labelText={strings('common.contactFields.isPublicProfile_create_labelText')} textStyle={{ color: colors.darkGreen }} />
          </View>

          <FormLabel bold required labelText={strings('common.contactFields.profileName_labelText')} />
          <FormInput
            value={this.props.profileName}
            placeholder={strings('common.contactFields.profileName_placeholder')}
            onChangeText={value => this.props.profileUpdate({ prop: 'profileName', value })}
            autoCorrect={false}
            autoCapitalize='none'
            inputStyle={styles.inputTextStyle}
          />
        </View>
      );
    }

    if (this.props.isEditMode) {
      if (this.props.publicProfileId === this.props.uid) {
        return (
          <View>
            <Spacer />
            <View style={styles.checkboxRowStyle}>
              <Icon
                name={'help-outline'}
                containerStyle={styles.helpIconStyle}
                onPress={() => this.setState({ isVisible: true })}
              />
              <FormLabel bold labelText={strings('common.contactFields.isPublicProfile_labelText')} textStyle={{ color: colors.darkGreen }} />
            </View>

            <FormLabel bold required labelText={strings('common.contactFields.profileName_labelText')} />
            <FormInput
              value={this.props.profileName}
              placeholder={strings('common.contactFields.profileName_placeholder')}
              onChangeText={value => this.props.profileUpdate({ prop: 'profileName', value })}
              autoCorrect={false}
              autoCapitalize='none'
              inputStyle={styles.inputTextStyle}
            />
          </View>
        );
      }

      return (
        <View>
          <FormLabel bold required labelText={strings('common.contactFields.profileName_labelText')} />
          <FormInput
            value={this.props.profileName}
            placeholder={strings('common.contactFields.profileName_placeholder')}
            onChangeText={value => this.props.profileUpdate({ prop: 'profileName', value })}
            autoCorrect={false}
            autoCapitalize='none'
            inputStyle={styles.inputTextStyle}
          />

          <View style={styles.checkboxRowStyle}>
            <Icon
              name={'help-outline'}
              containerStyle={styles.helpIconStyle}
              onPress={() => this.setState({ isVisible: true })}
            />
            <CheckBox
              title={strings('common.contactFields.setPublic_labelText')}
              checked={this.props.isPublicProfile}
              containerStyle={{ backgroundColor: colors.transparent, borderWidth: 0 }}
              onPress={() => this.props.propertyUpdate({ prop: 'isPublicProfile', value: !this.props.isPublicProfile })}
            />
          </View>
        </View>
      );
    }
  }

  /**
  * Renders the About section
  **/
  renderAboutSection() {
    if (this.props.isEditMode) {
      return (
        <View>
          <Spacer />
          <FormLabel required bold labelText={strings('common.contactFields.about_labelText')} />
          <FormInput
            value={this.props.about}
            placeholder={strings('common.contactFields.about_placeholder')}
            onChangeText={value => this.props.profileUpdate({ prop: 'about', value })}
            autoCorrect={false}
            autoCapitalize='none'
            multiline
            numberOfLines={4}
            inputStyle={styles.textBoxStyles}
          />

          <Spacer />
          <FormLabel required bold labelText={strings('common.contactFields.howIHelp_labelText_profile')} />
          <FormInput
            value={this.props.howIHelp}
            placeholder={strings('common.contactFields.howIHelp_placeholder')}
            onChangeText={value => this.props.profileUpdate({ prop: 'howIHelp', value })}
            autoCorrect={false}
            autoCapitalize='none'
            multiline
            numberOfLines={4}
            inputStyle={styles.textBoxStyles}
          />

          <Spacer />
          <FormLabel required bold labelText={strings('common.contactFields.whatINeed_labelText_profile')} />
          <FormInput
            value={this.props.whatINeed}
            placeholder={strings('common.contactFields.whatINeed_placeholder')}
            onChangeText={value => this.props.profileUpdate({ prop: 'whatINeed', value })}
            autoCorrect={false}
            autoCapitalize='none'
            multiline
            numberOfLines={4}
            inputStyle={styles.textBoxStyles}
          />
        </View>
      );
    }

    // NORMAL - VIEW MODE
    return (
      <Card>
        <FormLabel bold labelText={strings('common.contactFields.about_labelText')} />
        <FormLabel labelText={this.props.about} />

        <FormLabel bold labelText={strings('common.contactFields.howIHelp_labelText_profile')} />
        <FormLabel labelText={this.props.howIHelp} />

        <FormLabel bold labelText={strings('common.contactFields.whatINeed_labelText_profile')} />
        <FormLabel labelText={this.props.whatINeed} />
      </Card>
    );
  }

  /**
  * Renders the Experience section
  **/
  renderExperienceSection() {
    if (this.props.isEditMode) {
      const experienceList = addedExperience.map((data, index) => {
        return (
          <View key={index}>
            <View style={{ flexDirection: 'row', justifyContent: 'flex-start', marginTop: 10 }}>
              <Icon
                name='close'
                type="simple-line-icon"
                size={30}
                color={colors.red}
                containerStyle={{ marginLeft: 15 }}
                onPress={() => {
                  addedExperience.splice(index, 1);
                  this.setState({ addedExperience });
                  this.props.profileUpdate({ prop: 'experience', value: addedExperience });
                }}
              />
              <FormLabel bold labelText={strings('common.contactFields.experience_labelText')} />
              <Text style={styles.educationNumberTextStyle}>{index + 1}</Text>
            </View>

            <FormInput
              value={data.jobTitle}
              placeholder={strings('common.contactFields.experience_title_placeholder')}
              onChangeText={value => {
                addedExperience[index].jobTitle = value;
                this.props.profileUpdate({ prop: 'experience', value: addedExperience });
              }}
              autoCorrect={false}
              autoCapitalize='none'
              inputStyle={styles.inputTextStyle}
            />

            <FormInput
              value={data.jobCompany}
              placeholder={strings('common.contactFields.experience_company_placeholder')}
              onChangeText={value => {
                addedExperience[index].jobCompany = value;
                this.props.profileUpdate({ prop: 'experience', value: addedExperience });
              }}
              autoCorrect={false}
              autoCapitalize='none'
              inputStyle={styles.inputTextStyle}
            />

            <FormInput
              value={data.jobDates}
              placeholder={strings('common.contactFields.FromTo_placeholder')}
              onChangeText={value => {
                addedExperience[index].jobDates = value;
                this.props.profileUpdate({ prop: 'experience', value: addedExperience });
              }}
              autoCorrect={false}
              autoCapitalize='none'
              inputStyle={styles.inputTextStyle}
            />

            <FormInput
              value={data.jobLocation}
              placeholder={strings('common.contactFields.experience_location_placeholder')}
              onChangeText={value => {
                addedExperience[index].jobLocation = value;
                this.props.profileUpdate({ prop: 'experience', value: addedExperience });
              }}
              autoCorrect={false}
              autoCapitalize='none'
              inputStyle={styles.inputTextStyle}
            />

            <FormInput
              value={data.jobSummary}
              placeholder={strings('common.contactFields.experience_jobSummary_placeholder')}
              onChangeText={value => {
                addedExperience[index].jobSummary = value;
                this.props.profileUpdate({ prop: 'experience', value: addedExperience });
              }}
              autoCorrect={false}
              autoCapitalize='none'
              multiline
              numberOfLines={4}
              inputStyle={styles.textBoxStyles}
            />
          </View>
        );
      });

      return experienceList;
    }

    // NORMAL - VIEW MODE
    let isAddedExperienceEmpty = true;
    for (let i = 0; i < addedExperience.length; i++) {
      if (!isAddedExperienceEmpty) {
        break;
      }
      for (const property in addedExperience[i]) {
        if (addedExperience[i][property].length > 0) {
          isAddedExperienceEmpty = false;
          break;
        }
      }
    }

    if (!isAddedExperienceEmpty) {
      const experienceList = addedExperience.map((data, index) => {
        if (index > 0) {
          return (
            <View key={index}>
              <Divider style={styles.dividerStyle} />
              <FormLabel labelText={data.jobTitle} />
              <FormLabel labelText={data.jobCompany} />
              <FormLabel labelText={data.jobDates} />
              <FormLabel labelText={data.jobLocation} />
              <FormLabel labelText={data.jobSummary} />
            </View>
          );
        }
        return (
          <View key={index}>
            <FormLabel labelText={data.jobTitle} />
            <FormLabel labelText={data.jobCompany} />
            <FormLabel labelText={data.jobDates} />
            <FormLabel labelText={data.jobLocation} />
            <FormLabel labelText={data.jobSummary} />
          </View>
        );
      });

      return (
        <Card>
          <FormLabel bold labelText={strings('common.contactFields.experience_labelText')} />
          {experienceList}
        </Card>
      );
    }
  }

  /**
  * Renders the add button for the experience section
  **/
  renderExperienceAddButton() {
    if (this.props.isEditMode) {
      return (
        <TextButton
          rightText={strings('common.buttons.add')}
          rightTextStyle={{ fontSize: 20, fontWeight: 'normal' }}
          containerStyle={{ marginTop: 15 }}
          onPress={() => {
            addedExperience.push({ jobTitle: '', jobCompany: '', jobDates: '', jobLocation: '', jobSummary: '' });
            this.setState({ addedExperience });
          }}
        />
      );
    }
  }

  /**
  * Renders the Education section
  **/
  renderEducationSection() {
    if (this.props.isEditMode) {
      const educationList = addedEducation.map((data, index) => {
        return (
          <View key={index}>
            <View style={{ flexDirection: 'row', justifyContent: 'flex-start', marginTop: 10 }}>
              <Icon
                name='close'
                type="simple-line-icon"
                size={30}
                color={colors.red}
                containerStyle={{ marginLeft: 15 }}
                onPress={() => {
                  addedEducation.splice(index, 1);
                  this.setState({ addedEducation });
                  this.props.profileUpdate({ prop: 'education', value: addedEducation });
                }}
              />
              <FormLabel bold labelText={strings('common.contactFields.education_labelText')} />
              <Text style={styles.educationNumberTextStyle}>{index + 1}</Text>
            </View>

            <FormInput
              value={data.school}
              placeholder={strings('common.contactFields.education_school_placeholder')}
              onChangeText={value => {
                addedEducation[index].school = value;
                this.props.profileUpdate({ prop: 'education', value: addedEducation });
              }}
              autoCorrect={false}
              autoCapitalize='none'
              inputStyle={styles.inputTextStyle}
            />

            <FormInput
              value={data.degree}
              placeholder={strings('common.contactFields.education_degreeType_placeholder')}
              onChangeText={value => {
                addedEducation[index].degree = value;
                this.props.profileUpdate({ prop: 'education', value: addedEducation });
              }}
              autoCorrect={false}
              autoCapitalize='none'
              inputStyle={styles.inputTextStyle}
            />

            <FormInput
              value={data.fieldOfStudy}
              placeholder={strings('common.contactFields.education_fieldOfStudy_placeholder')}
              onChangeText={value => {
                addedEducation[index].fieldOfStudy = value;
                this.props.profileUpdate({ prop: 'education', value: addedEducation });
              }}
              autoCorrect={false}
              autoCapitalize='none'
              inputStyle={styles.inputTextStyle}
            />

            <FormInput
              value={data.schoolDates}
              placeholder={strings('common.contactFields.FromTo_placeholder')}
              onChangeText={value => {
                addedEducation[index].schoolDates = value;
                this.props.profileUpdate({ prop: 'education', value: addedEducation });
              }}
              autoCorrect={false}
              autoCapitalize='none'
              inputStyle={styles.inputTextStyle}
            />

            <FormInput
              value={data.educationSummary}
              placeholder={strings('common.contactFields.education_educationSummary_placeholder')}
              onChangeText={value => {
                addedEducation[index].educationSummary = value;
                this.props.profileUpdate({ prop: 'education', value: addedEducation });
              }}
              autoCorrect={false}
              autoCapitalize='none'
              multiline
              numberOfLines={4}
              inputStyle={styles.textBoxStyles}
            />
          </View>
        );
      });

      return educationList;
    }

    // NORMAL - VIEW MODE
    let isAddedEducationEmpty = true;
    for (let i = 0; i < addedEducation.length; i++) {
      if (!isAddedEducationEmpty) {
        break;
      }
      for (const property in addedEducation[i]) {
        if (addedEducation[i][property].length > 0) {
          isAddedEducationEmpty = false;
          break;
        }
      }
    }

    if (!isAddedEducationEmpty) {
      const educationList = addedEducation.map((data, index) => {
        if (index > 0) {
          return (
            <View key={index}>
              <Divider style={styles.dividerStyle} />
              <FormLabel labelText={data.school} />
              <FormLabel labelText={data.degree} />
              <FormLabel labelText={data.fieldOfStudy} />
              <FormLabel labelText={data.schoolDates} />
              <FormLabel labelText={data.educationSummary} />
            </View>
          );
        }
        return (
          <View key={index}>
            <FormLabel labelText={data.school} />
            <FormLabel labelText={data.degree} />
            <FormLabel labelText={data.fieldOfStudy} />
            <FormLabel labelText={data.schoolDates} />
            <FormLabel labelText={data.educationSummary} />
          </View>
        );
      });

      return (
        <Card>
          <FormLabel bold labelText={strings('common.contactFields.education_labelText')} />
          {educationList}
        </Card>
      );
    }
  }

  /**
  * Renders the add button for the education section
  **/
  renderEducationAddButton() {
    if (this.props.isEditMode) {
      return (
        <TextButton
          rightText={strings('common.buttons.add')}
          rightTextStyle={{ fontSize: 20, fontWeight: 'normal' }}
          containerStyle={{ marginTop: 15 }}
          onPress={() => {
            addedEducation.push({ school: '', degree: '', fieldOfStudy: '', schoolDates: '', educationSummary: '' });
            this.setState({ addedEducation });
          }}
        />
      );
    }
  }

  /**
  * Renders the primary phone section
  **/
  renderPrimaryPhoneSection() {
    if (this.props.isEditMode) {
      return (
        <View>
          <Spacer />
          <FormLabel bold labelText={strings('common.contactFields.phone_primary_labelText')} />
          <FormInput
            value={this.props.primaryPhone}
            placeholder={strings('common.contactFields.phone_placeholder')}
            onChangeText={value => this.props.profileUpdate({ prop: 'primaryPhone', value })}
            autoCorrect={false}
            autoCapitalize='none'
            inputStyle={styles.inputTextStyle}
          />
        </View>
      );
    }

    // NORMAL - VIEW MODE
    const { primaryPhone } = this.props;
    if (!primaryPhone) {
      return;
    }

    return (
      <Card>
        <FormLabel bold labelText={strings('common.contactFields.phone_primary_labelText')} />
        <FormLabel labelText={this.props.primaryPhone} />
      </Card>
    );
  }

  /**
  * Renders the secondary phone section
  **/
  renderSecondaryPhoneSection() {
    if (this.props.isEditMode) {
      return (
        <View>
          <Spacer />
          <FormLabel bold labelText={strings('common.contactFields.phone_secondary_labelText')} />
          <FormInput
            value={this.props.secondaryPhone}
            placeholder={strings('common.contactFields.phone_placeholder')}
            onChangeText={value => this.props.profileUpdate({ prop: 'secondaryPhone', value })}
            autoCorrect={false}
            autoCapitalize='none'
            inputStyle={styles.inputTextStyle}
          />
        </View>
      );
    }

    // NORMAL - VIEW MODE
    const { secondaryPhone } = this.props;
    if (!secondaryPhone) {
      return;
    }

    return (
      <Card>
        <FormLabel bold labelText={strings('common.contactFields.phone_secondary_labelText')} />
        <FormLabel labelText={this.props.secondaryPhone} />
      </Card>
    );
  }

  /**
  * Renders the work phone section
  **/
  renderWorkPhoneSection() {
    if (this.props.isEditMode) {
      return (
        <View>
          <Spacer />
          <FormLabel bold labelText={strings('common.contactFields.phone_work_labelText')} />
          <FormInput
            value={this.props.workPhone}
            placeholder={strings('common.contactFields.phone_placeholder')}
            onChangeText={value => this.props.profileUpdate({ prop: 'workPhone', value })}
            autoCorrect={false}
            autoCapitalize='none'
            inputStyle={styles.inputTextStyle}
          />

          <FormLabel bold labelText={strings('common.contactFields.extension_labelText')} />
          <FormInput
            value={this.props.extension}
            placeholder={strings('common.contactFields.extension_placeholder')}
            onChangeText={value => this.props.profileUpdate({ prop: 'extension', value })}
            autoCorrect={false}
            autoCapitalize='none'
            inputStyle={styles.inputTextStyle}
          />
        </View>
      );
    }

    // NORMAL - VIEW MODE
    const { workPhone, extension } = this.props;
    if (!workPhone && !extension) {
      return;
    }

    return (
      <Card>
        <FormLabel bold labelText={strings('common.contactFields.phone_work_labelText')} />
        <FormLabel labelText={this.props.workPhone} />

        <FormLabel bold labelText={strings('common.contactFields.extension_labelText')} />
        <FormLabel labelText={this.props.extension} />
      </Card>
    );
  }

  /**
  * Renders the fax phone section
  **/
  renderFaxSection() {
    if (this.props.isEditMode) {
      return (
        <View>
          <Spacer />
          <FormLabel bold labelText={strings('common.contactFields.fax_labelText')} />
          <FormInput
            value={this.props.fax}
            placeholder={strings('common.contactFields.phone_placeholder')}
            onChangeText={value => this.props.profileUpdate({ prop: 'fax', value })}
            autoCorrect={false}
            autoCapitalize='none'
            inputStyle={styles.inputTextStyle}
          />
        </View>
      );
    }

    // NORMAL - VIEW MODE
    const { fax } = this.props;
    if (!fax) {
      return;
    }

    return (
      <Card>
        <FormLabel bold labelText={strings('common.contactFields.fax_labelText')} />
        <FormLabel labelText={this.props.fax} />
      </Card>
    );
  }

  /**
  * Renders the email section
  **/
  renderEmailSection() {
    if (this.props.isEditMode) {
      return (
        <View>
          <Spacer />
          <FormLabel bold labelText={strings('common.contactFields.email_labelText')} />
          <FormInput
            value={this.props.profileEmail}
            placeholder={strings('common.contactFields.email_placeholder')}
            onChangeText={value => this.props.profileUpdate({ prop: 'profileEmail', value })}
            autoCorrect={false}
            autoCapitalize='none'
            inputStyle={styles.inputTextStyle}
          />
        </View>
      );
    }

    // NORMAL - VIEW MODE
    const { profileEmail } = this.props;
    if (!profileEmail) {
      return;
    }

    return (
      <Card>
        <FormLabel bold labelText={strings('common.contactFields.email_labelText')} />
        <FormLabel labelText={this.props.profileEmail} />
      </Card>
    );
  }

  /**
  * Renders the website section
  **/
  renderWebsiteSection() {
    if (this.props.isEditMode) {
      return (
        <View>
          <Spacer />
          <FormLabel bold labelText={strings('common.contactFields.website_labelText')} />
          <FormInput
            value={this.props.website}
            placeholder={strings('common.contactFields.website_placeholder')}
            onChangeText={value => this.props.profileUpdate({ prop: 'website', value })}
            autoCorrect={false}
            autoCapitalize='none'
            inputStyle={styles.inputTextStyle}
          />
        </View>
      );
    }

    // NORMAL - VIEW MODE
    const { website } = this.props;
    if (!website) {
      return;
    }

    return (
      <Card>
        <FormLabel bold labelText={strings('common.contactFields.website_labelText')} />
        <FormLabel labelText={this.props.website} />
      </Card>
    );
  }

  /**
  * Renders the address section
  **/
  renderAddressSection() {
    if (this.props.isEditMode) {
      return (
        <View>
          <Spacer />
          <FormLabel bold labelText={strings('common.contactFields.address_labelText')} />
          <FormInput
            value={this.props.street}
            placeholder={strings('common.contactFields.address_placeholder_street')}
            onChangeText={value => this.props.profileUpdate({ prop: 'street', value })}
            autoCorrect={false}
            autoCapitalize='none'
            inputStyle={styles.inputTextStyle}
          />
          <FormInput
            value={this.props.address2}
            placeholder={strings('common.contactFields.address_placeholder_address2')}
            onChangeText={value => this.props.profileUpdate({ prop: 'address2', value })}
            autoCorrect={false}
            autoCapitalize='none'
            inputStyle={styles.inputTextStyle}
          />
          <FormInput
            value={this.props.city}
            placeholder={strings('common.contactFields.address_placeholder_city')}
            onChangeText={value => this.props.profileUpdate({ prop: 'city', value })}
            autoCorrect={false}
            autoCapitalize='none'
            inputStyle={styles.inputTextStyle}
          />
          <FormInput
            value={this.props.region}
            placeholder={strings('common.contactFields.address_placeholder_region')}
            onChangeText={value => this.props.profileUpdate({ prop: 'region', value })}
            autoCorrect={false}
            autoCapitalize='none'
            inputStyle={styles.inputTextStyle}
          />
          <FormInput
            value={this.props.postalCode}
            placeholder={strings('common.contactFields.address_placeholder_postalCode')}
            onChangeText={value => this.props.profileUpdate({ prop: 'postalCode', value })}
            autoCorrect={false}
            autoCapitalize='none'
            inputStyle={styles.inputTextStyle}
          />
          <FormInput
            value={this.props.country}
            placeholder={strings('common.contactFields.address_placeholder_country')}
            onChangeText={value => this.props.profileUpdate({ prop: 'country', value })}
            autoCorrect={false}
            autoCapitalize='none'
            inputStyle={styles.inputTextStyle}
          />
        </View>
      );
    }

    // NORMAL - VIEW MODE
    const { street, address2, city, region, postalCode, country } = this.props;
    if (!street && !address2 && !city && !region && !postalCode && !country) {
      return;
    }

    return (
      <Card>
        <FormLabel bold labelText={strings('common.contactFields.address_labelText')} />
        <FormLabel labelText={this.props.street} />
        <FormLabel labelText={this.props.address2} />
        <FormLabel labelText={this.props.city} />
        <FormLabel labelText={this.props.region} />
        <FormLabel labelText={this.props.postalCode} />
        <FormLabel labelText={this.props.country} />
      </Card>
    );
  }

  /**
  * Renders the keyword section
  **/
  renderKeywordSection() {
    if (this.props.isEditMode) {
      return (
        <View>
          <Spacer />
          <FormLabel bold labelText={strings('common.contactFields.keywordsAdd_labelText')} />
          <Text style={{ marginLeft: 10, fontSize: 10 }}>{strings('common.contactFields.keywordsAdd_labelText2')}</Text>
          <View style={styles.inputAndButtonRow}>
            <FormInput
              value={this.state.keyword}
              placeholder={strings('common.contactFields.keywords_placeholder')}
              onChangeText={value => this.setState({ keyword: value })}
              autoCorrect={false}
              autoCapitalize='none'
              multiline
              numberOfLines={4}
              containerStyle={styles.halfInputStyle}
              inputStyle={styles.keywordInputTextStyle}
            />
            <Button
              onPress={() => this.onAddKeywordPress()}
              title={strings('common.buttons.add')}
              buttonStyle={styles.halfButtonStyle}
            />
          </View>
          <Spacer />
          <View style={styles.keywordViewStyle}>
            {this.renderKeywords()}
          </View>
        </View>
      );
    }

    // NORMAL - VIEW MODE
    if (this.state.keywords.length === 0) {
      return;
    }
    return (
      <Card>
        <View style={styles.keywordViewStyle}>
          {this.renderKeywords()}
        </View>
      </Card>
    );
  }

  /**
  * Renders each keyword onto the screen
  **/
  renderKeywords() {
    const keywordArray = this.state.keywords.map((data, index) => {
      return (
        <Keyword
          key={index}
          title={data}
          onPressX={() => this.removeKeyword(index)}
          displayX={this.props.isEditMode}
          index={index}
        />
      );
    });
    return keywordArray;
  }

  /**
  * Renders the error section
  **/
  renderErrorSection() {
    if (this.props.isEditMode) {
      return (
        <View>
          <FormMessage error={this.props.error} />
        </View>
      );
    }
  }

  /**
  * Render method
  **/
  render() {
    if (this.props.isCreateMode) {
      return (
        <View style={{ backgroundColor: colors.white }}>
          {this.renderAvatarBizCardSlider()}
          {this.renderProfileNameSection()}

          {this.renderAboutSection()}

          {this.renderPrimaryPhoneSection()}
          {this.renderEmailSection()}
          <Spacer />

          <Confirm
            visible={this.state.isVisible}
            onOkay={this.onOkay.bind(this)}
          >
            {strings('profile.publicDescription')}
          </Confirm>
          {this.renderErrorSection()}
        </View>
      );
    }

    return (
      <View>
        {this.renderAvatarBizCardSlider()}
        {this.renderKeywordSection()}

        {this.renderProfileNameSection()}

        {this.renderAboutSection()}
        {this.renderExperienceSection()}
        {this.renderExperienceAddButton()}

        {this.renderEducationSection()}
        {this.renderEducationAddButton()}

        {this.renderPrimaryPhoneSection()}
        {this.renderSecondaryPhoneSection()}
        {this.renderWorkPhoneSection()}
        {this.renderFaxSection()}

        {this.renderEmailSection()}
        {this.renderWebsiteSection()}

        {this.renderAddressSection()}
        <Spacer />

        <Confirm
          visible={this.state.isVisible}
          onOkay={this.onOkay.bind(this)}
        >
          {strings('profile.publicDescription')}
        </Confirm>
        {this.renderErrorSection()}
      </View>
    );
  }
}

const styles = {
  slideStyle: {
    width: SCREEN_WIDTH,
  },
  detailsSectionStyle: {
    backgroundColor: colors.white,
    borderBottomWidth: 1,
    borderColor: colors.middleGrey
  },
  dividerStyle: {
    backgroundColor: colors.middleGrey,
    marginTop: 10,
    marginBottom: 15
  },
  textBoxStyles: {
    flex: 1,
    width: '100%',
    color: colors.black
  },
  inputAndButtonRow: {
    flex: 2,
    marginTop: 15,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  halfInputStyle: {
    flex: 1
  },
  keywordInputTextStyle: {
    width: '100%',
  },
  halfButtonStyle: {
    backgroundColor: colors.buttonBlue,
    flex: 1,
    borderRadius: 5
  },
  centeredInputContainerStyle: {
    borderBottomWidth: 0,
    marginLeft: 15,
    marginRight: 0
  },
  centeredInputTextStyle: {
    textAlign: 'center',
    color: colors.black
  },
  centeredTextBoxStyles: {
    textAlign: 'center',
    flex: 1,
    width: '100%',
    color: colors.black
  },
  inputTextStyle: {
    width: '100%',
    color: colors.black
  },
  nameTextStyle: {
    fontSize: 22,
    fontWeight: 'bold'
  },
  keywordViewStyle: {
    flex: 1,
    flexDirection: 'row',
    flexWrap: 'wrap'
  },
  keywordStyle: {
    borderWidth: 1,
    borderColor: colors.middleGrey,
    borderRadius: 15,
  },
  checkboxRowStyle: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'flex-start'
  },
  helpIconStyle: {
    paddingLeft: 15,
    marginRight: -10
  },
  educationNumberTextStyle: {
    color: colors.orange,
    fontSize: 15,
    fontWeight: 'bold',
    marginHorizontal: 10,
    alignSelf: 'center'
  }
};

/**
* If you add any items here be sure to update the lists in
* ProfileEditScreen, ProfileActions, ProfileFormReducer, and UserCreateScreen
* Also update the onDuplicateButtonPress method of ProfileAvatar.js
**/
const mapStateToProps = (state) => {
  const {
    profileBizCardImg,
    profileAvatarImg,
    firstName,
    lastName,
    fullName,
    headline,
    location,
    primaryPhone,
    secondaryPhone,
    extension,
    titleAndCompany,
    about,
    howIHelp,
    whatINeed,
    experience,
    education,
    workPhone,
    fax,
    profileEmail,
    website,
    street,
    address2,
    city,
    region,
    postalCode,
    country,
    keywords,
    referralId,
    profileName,
    error,
    uid
  } = state.profileForm;

  const { isPublicProfile, publicProfileId, tagferId } = state.properties;

  return {
    profileBizCardImg,
    profileAvatarImg,
    firstName,
    lastName,
    fullName,
    headline,
    location,
    primaryPhone,
    secondaryPhone,
    extension,
    titleAndCompany,
    about,
    howIHelp,
    whatINeed,
    experience,
    education,
    workPhone,
    fax,
    profileEmail,
    website,
    street,
    address2,
    city,
    region,
    postalCode,
    country,
    keywords,
    referralId,
    profileName,
    error,
    uid,
    isPublicProfile,
    publicProfileId,
    tagferId
  };
};

export default connect(mapStateToProps, { profileUpdate, propertyUpdate })(ProfileForm);
