/** Contains the base fields for Social Display **/
import React, { Component } from 'react';
import { Animated, Dimensions, Linking, ScrollView, Share, View } from 'react-native';
import { Card, Divider, Icon } from 'react-native-elements';
import { connect } from 'react-redux';
import { socialFormReset } from '../../actions';
import ProfileAvatar from '../ProfileAvatar';
import BizCard from '../BizCard';
import { FormLabel, Keyword, Spacer } from '../common';
import { SOCIAL_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 DEV_LINKING_BASE_URL = privateKeys.deepLinking.devBaseUrl;
const TAGFER_BASE_URL = privateKeys.deepLinking.tagferBaseUrl;
const scrollX = new Animated.Value(0);

class SocialForm extends Component {

  /**
  * Component Will Unmount
  **/
  componentWillUnmount() {
    this.props.socialFormReset();
  }

  /**
  * Opens the normal hardware process for sharing something via social, sms, etc
  * uid - the uid for the profile to be shared
  **/
  shareLink(tagferId, uid) {
    Share.share(
      {
        message: `Add me on Tagfer! ${DEV_LINKING_BASE_URL}${tagferId}/${uid}`,
        title: 'Add me on Tagfer!',
        url: `${TAGFER_BASE_URL}${tagferId}/${uid}`
      },
      {
        tintColor: 0x056ecf,
        excludedActivityTypes: [
          'com.apple.UIKit.activity.PostToWeibo',
          'com.apple.UIKit.activity.Print',
          'com.apple.UIKit.activity.CopyToPasteboard',
          'com.apple.UIKit.activity.AssignToContact',
          'com.apple.UIKit.activity.SaveToCameraRoll',
          'com.apple.UIKit.activity.AddToReadingList',
          'com.apple.UIKit.activity.PostToFlickr',
          'com.apple.UIKit.activity.PostToVimeo',
          'com.apple.UIKit.activity.PostToTencentWeibo',
          'com.apple.UIKit.activity.AirDrop',
          'com.apple.UIKit.activity.OpenInIBooks',
          'com.apple.UIKit.activity.MarkupAsPDF',
          'com.apple.reminders.RemindersEditorExtension', //Reminders
          'com.apple.mobilenotes.SharingExtension', // Notes
          'com.apple.mobileslideshow.StreamShareService', // iCloud Photo Sharing - This also does nothing :{

          // Not supported
          'com.linkedin.LinkedIn.ShareExtension', //LinkedIn
          'pinterest.ShareExtension', //Pinterest
          'com.google.GooglePlus.ShareExtension', //Google +
          'com.tumblr.tumblr.Share-With-Tumblr', //Tumblr
          'wefwef.YammerShare', //Yammer
          'com.hootsuite.hootsuite.HootsuiteShareExt', //HootSuite
          'net.naan.TwitterFonPro.ShareExtension-Pro', //Echofon
          'net.whatsapp.WhatsApp.ShareExtension' //WhatsApp
        ]
      }
    );
  }

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

    if (this.props.isAddMode) {
      return (
        <View>
          <Spacer />
          {this.renderDetailsSection()}
          <Spacer />
        </View>
      );
    }

    return (
      <View>
        <ScrollView
          horizontal
          pagingEnabled
          showsHorizontalScrollIndicator={false}
          onScroll={Animated.event(
            [{ nativeEvent: { contentOffset: { x: scrollX } } }]
          )}
          scrollEventThrottle={16}
        >
          <View style={styles.slideStyle}>
            <ProfileAvatar
              {...this.props}
              formType={SOCIAL_FORM}
              isEditMode={this.props.isEditMode}
            />
            {this.renderDetailsSection()}
          </View>

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

        <View style={styles.dotsStyle}>
          {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.renderConnectionButtons()}
      </View>
    );
  }

  /**
  * Renders the top section under the avatar
  **/
  renderDetailsSection() {
    if (this.props.isAddMode) {
      return (
        <View style={{ flex: 1, flexDirection: 'column', alignItems: 'center', marginLeft: -10 }}>
          <FormLabel bold labelText={`@${this.props.navigation.state.params.tagferId}`} textStyle={{ color: colors.darkGreen, fontSize: 18 }} />
          <FormLabel bold labelText={this.props.fullName} textStyle={{ fontSize: 22 }} />
          <FormLabel bold labelText={this.props.headline} textStyle={{ fontSize: 15 }} />
          <FormLabel bold labelText={this.props.titleAndCompany} textStyle={{ fontSize: 15 }} />
          <FormLabel bold labelText={this.props.location} textStyle={{ fontSize: 15 }} />
        </View>
      );
    }
    return (
      <View style={{ flex: 1, flexDirection: 'column', alignItems: 'center', marginLeft: -10 }}>
        <FormLabel bold labelText={`@${this.props.navigation.state.params.otherTagferId}`} textStyle={{ color: colors.darkGreen, fontSize: 18 }} />
        <FormLabel bold labelText={this.props.fullName} textStyle={{ fontSize: 22 }} />
        <FormLabel bold labelText={this.props.headline} textStyle={{ fontSize: 15 }} />
        <FormLabel bold labelText={this.props.titleAndCompany} textStyle={{ fontSize: 15 }} />
        <FormLabel bold labelText={this.props.location} textStyle={{ fontSize: 15 }} />
      </View>
    );
  }

  /**
  * Renders the various buttons for this connection
  **/
  renderConnectionButtons() {
    if (this.props.isAddMode) {
      return <Divider style={styles.dividerStyle} />;
    }
    const { otherUserId, myFriendId, otherFriendId } = this.props.navigation.state.params;
    // NORMAL MODE
    return (
      <View>
        <Divider style={styles.dividerStyle} />

        <View style={styles.iconViewContainerStyle}>
          <Icon
            name={'phone'}
            type="simple-line-icon"
            size={30}
            color={colors.darkGreen}
            containerStyle={styles.iconStyle}
            onPress={() => Linking.openURL(`tel:+${this.props.primaryPhone}`)}
          />
          <Icon
            name={'action-redo'}
            type="simple-line-icon"
            size={30}
            color={colors.buttonBlue}
            containerStyle={styles.iconStyle}
            onPress={() => this.shareLink(this.props.tagferId, this.props.userId)}
          />
          <Icon
            name={'speech'}
            type="simple-line-icon"
            size={30}
            color={colors.darkBlue}
            containerStyle={styles.iconStyle}
            onPress={() => this.props.navigation.navigate('messageScreen', { otherUserId, myFriendId, otherFriendId })}
          />
          <Icon
            name={'note'}
            type="simple-line-icon"
            size={30}
            color={colors.orange}
            containerStyle={styles.iconStyle}
            onPress={() => this.props.navigation.navigate('socialNotesScreen', { friendId: myFriendId })}
          />
        </View>
        <Divider style={styles.dividerStyle} />
      </View>
    );
  }

  /**
  * Renders the About section
  **/
  renderAboutSection() {
    if (this.props.isAddMode) {
      return;
    }

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

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

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

  /**
  * Renders the Experience section
  **/
  renderExperienceSection() {
    if (this.props.isAddMode) {
      return;
    }

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

    if (!isAddedExperienceEmpty) {
      const experienceList = this.props.education.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 Education section
  **/
  renderEducationSection() {
    if (this.props.isAddMode) {
      return;
    }

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

    if (!isAddedEducationEmpty) {
      const educationList = this.props.education.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 primary phone section
  **/
  renderPrimaryPhoneSection() {
    if (this.props.isAddMode) {
      return;
    }

    // NORMAL 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.isAddMode) {
      return;
    }

    // NORMAL 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.isAddMode) {
      return;
    }

    // NORMAL 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.isAddMode) {
      return;
    }

    // NORMAL 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.isAddMode) {
      return;
    }

    // NORMAL 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.isAddMode) {
      return;
    }

    // NORMAL 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.isAddMode) {
      return;
    }

    // NORMAL 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.navigation.state.params.keywords || this.props.navigation.state.params.keywords.length === 0) {
      return;
    }
    return (
      <Card>
        <View style={styles.keywordViewStyle}>
          {this.renderKeywords()}
        </View>
      </Card>
    );
  }

  /**
  * Renders each keyword onto the screen
  **/
  renderKeywords() {
    if (!this.props.keywords || !this.props.navigation.state.params.keywords) {
      return;
    }
    let keywordArray = [];
    if (this.props.isAddMode) {
      keywordArray = this.props.navigation.state.params.keywords.map((data, index) => {
        return (
          <Keyword
            key={index}
            title={data}
            index={index}
          />
        );
      });
    } else {
      keywordArray = Object.values(this.props.keywords).map((data, index) => {
        return (
          <Keyword
            key={index}
            title={data}
            index={index}
          />
        );
      });
    }
    return keywordArray;
  }

  /**
  * Render method
  **/
  render() {
    return (
      <View>
        <View style={styles.whiteBackground}>
          {this.renderAvatarBizCardSlider()}
        </View>
        {this.renderKeywordSection()}

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

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

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

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

const styles = {
  slideStyle: {
    width: SCREEN_WIDTH,
  },
  whiteBackground: {
    backgroundColor: colors.white
  },
  dotsStyle: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    backgroundColor: colors.white
  },
  dividerStyle: {
    backgroundColor: colors.offWhite,
    marginTop: 10,
    marginBottom: 15
  },
  iconViewContainerStyle: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center'
  },
  iconStyle: {
    marginLeft: 20,
    marginRight: 20
  },
  keywordViewStyle: {
    flex: 1,
    flexDirection: 'row',
    flexWrap: 'wrap'
  }
};

/**
* If you add any items here be sure to update the lists in
* SocialAddScreen, SocialEditScreen, SocialActions, and SocialReducer
**/
const mapStateToProps = (state) => {
  const {
    socialBizCardImg,
    socialAvatarImg,
    profileName,
    titleAndCompany,
    firstName,
    lastName,
    fullName,
    headline,
    location,
    profileEmail,
    primaryPhone,
    secondaryPhone,
    extension,
    about,
    howIHelp,
    whatINeed,
    experience,
    education,
    workPhone,
    fax,
    website,
    street,
    address2,
    city,
    region,
    postalCode,
    country,
    keywords,
    referralId,
    userId,
    profileId,
    friendId,
    tagferId,
    loading,
    error,
    success
  } = state.socialContacts;

  return {
    socialBizCardImg,
    socialAvatarImg,
    profileName,
    titleAndCompany,
    firstName,
    lastName,
    fullName,
    headline,
    location,
    profileEmail,
    primaryPhone,
    secondaryPhone,
    extension,
    about,
    howIHelp,
    whatINeed,
    experience,
    education,
    workPhone,
    fax,
    website,
    street,
    address2,
    city,
    region,
    postalCode,
    country,
    keywords,
    referralId,
    userId,
    profileId,
    friendId,
    tagferId,
    loading,
    error,
    success
  };
};

export default connect(mapStateToProps, {
  socialFormReset
})(SocialForm);
