/** Screen for creating default User Profile **/
import React from 'react';
import { Button, FormInput, Alert } from 'react-native-elements';
import { KeyboardAvoidingView, Platform, ScrollView, Text, View, TouchableOpacity } from 'react-native';
import OpenAppSettings from 'react-native-app-settings';
import ImagePicker from 'react-native-image-picker';
import Permissions from 'react-native-permissions';

import { strings } from '../../locales/i18n';
import { loadSignupState, saveSignupState } from '../../realm/actions/AuthActions';

import { FormLabel, Spacer, TextButton } from '../../components/common';
import styles from './styles';
import TagferAvatar from '../../components/new/TagferAvatar';
import { isEmail } from '../../utils/aux';

export default class SignupScreenFour extends React.Component {
  static navigationOptions = {
    title: strings('userCreateFlow.defaultProfileCreate.title'),
    headerStyle: { borderBottomWidth: 0 },
    headerTintColor: '#0D497E',
    headerRight: <Text style={styles.navigationHeaderRightStyle}>4/6</Text>
  };

  constructor(props) {
    super(props);
    this.state = {
      jobTitle: '',
      companyName: '',
      companyEmail: '',
      companyPhoneNumber: '',
      photoBytes: '',
      loading: false
    };

    loadSignupState(4).then(result => {
      this.isUpdate = result.isUpdate;
      this.setState({ ...result.prevState });
    });

    this.renderAvatarPhoto = this.renderAvatarPhoto.bind(this);
    this.onUploadPhotoPress = this.onUploadPhotoPress.bind(this);
    this.onTakePhotoPress = this.onTakePhotoPress.bind(this);
  }

  onSaveButtonPress() {
    this.props.navigation.navigate('signup5');
    saveSignupState(4, this.state, this.isUpdate);
  }

  async onTakePhotoPress() {
    this.setState({ loading: true });
    try {
      const response = await Permissions.request('camera');
      if (response !== 'authorized') {
        this.createSettingsAlert('Camera Access Deinied', 'To enable access, tap Settings and turn on Camera');
        this.setState({ loading: false });
      } else {
        ImagePicker.launchCamera({ mediaType: 'photo' }, result => this.setState({ loading: false, photoBytes: result.data }));
      }
    } catch (error) {
      console.log(error);
    }
  }

  async onUploadPhotoPress() {
    this.setState({ loading: true });
    try {
      const response = await Permissions.request('photo');
      if (response !== 'authorized') {
        this.createSettingsAlert('Photos Access Deinied', 'To enable access, tap Settings and turn on Photos');
        this.setState({ loading: false });
      } else {
        ImagePicker.launchImageLibrary({ allowsEditing: true }, result => this.setState({ loading: false, photoBytes: result.data }));
      }
    } catch (error) {
      console.log(error);
    }
  }

  createSettingsAlert(title, message) {
    Alert.alert(
      title,
      message,
      [
        { text: 'Cancel', style: 'cancel' },
        { text: 'Settings', onPress: () => OpenAppSettings.open() }
      ],
      { cancelable: false }
    );
  }

  isDisabled() {
    const { jobTitle, companyName, companyEmail, companyPhoneNumber, loading } = this.state;
    return !jobTitle || !companyName || !isEmail(companyEmail) || companyPhoneNumber.length < 10 || loading;
  }

  renderLinkedInButtons() {
    return (
      <TextButton
        rightText={strings('common.contactFields.linkedIn_import')}
        rightTextStyle={{ fontSize: 18, fontWeight: 'normal', color: '#53ACF0' }}
        containerStyle={{ marginLeft: -2, marginTop: 15 }}
        onPress={this.openLinkedInWebView}
        disabled
      />
    );
  }

  renderAvatarPhoto() {
    let photoURL = '';
    if (this.state.photoBytes) {
      photoURL = `data:image/jpeg;base64,${this.state.photoBytes}`;
    }

    return (
      <View style={styles.avatarStyle}>
        <TagferAvatar size='xlarge' photoURL={photoURL} style={{ marginLeft: 25 }} color='#47C0E237' />
        {this.renderPhotoButtons()}
      </View>
    );
  }

  renderPhotoButtons() {
    return (
      <View style={styles.buttonContainerStyle}>
        <TouchableOpacity onPress={this.onUploadPhotoPress} disabled={this.props.loading}>
          <Text style={styles.textButtonStyle}>{strings('common.buttons.uploadPhoto')}</Text>
        </TouchableOpacity>

        <Text style={styles.photoButtonsOrTextStyle}>{strings('profile.or')}</Text>

        <TouchableOpacity onPress={this.onTakePhotoPress} disabled={this.props.loading}>
          <Text style={styles.textButtonStyle}>{strings('common.buttons.takePhoto')}</Text>
        </TouchableOpacity>
      </View>
    );
  }

  renderInputComponents(labelString, inputPlaceholderText, onChangeInput) {
    return (
      <View>
        <FormLabel
          labelText={labelString}
          textStyle={styles.labelStyle}
        />
        <FormInput
          underlineColorAndroid={styles.colors.greyBlue}
          value={this.state[onChangeInput]}
          placeholder={inputPlaceholderText}
          onChangeText={value => this.setState({ [onChangeInput]: value })}
          inputStyle={styles.inputTextStyle}
          autoCorrect={false}
          autoCapitalize='none'
        />
      </View>
    );
  }

  renderContent() {
    return (
    <View style={{ flex: 1 }}>
      <ScrollView contentContainerStyle={styles.parentContentScrollViewStyle} keyboardShouldPersistTaps="handled">
        <View style={{ flex: 1 }}>
          {/* INSTRUCTIONS */}
          <Text style={styles.instructions}>{strings('userCreateFlow.defaultProfileCreate.instructions')}</Text>
          <Spacer />
          <View style={{ flex: 1, flexDirection: 'column', justifyContent: 'center' }}>
            {this.renderAvatarPhoto()}
            <Spacer />
            {this.renderLinkedInButtons()}
            {this.renderInputComponents(strings('common.contactFields.company_title_labelText'), strings('common.contactFields.company_title_placeholder'), 'jobTitle')}
            {this.renderInputComponents(strings('common.contactFields.company_name_labelText'), strings('common.contactFields.company_name_placeholder'), 'companyName')}
            {this.renderInputComponents(strings('common.contactFields.company_address_labelText'), strings('common.contactFields.company_address_placeholder'), 'companyEmail')}
            {this.renderInputComponents(strings('common.contactFields.company_number_labelText'), strings('common.contactFields.company_number_placeholder'), 'companyPhoneNumber')}
            <Text style={{ marginLeft: 17, color: '#ABABAB' }}>{strings('userCreateFlow.defaultProfileCreate.no_verification_needed')}</Text>
            <Spacer />
          </View>
        </View>
      </ScrollView>

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

  render() {
    if (Platform.OS === 'android') {
      return this.renderContent();
    }

    // IOS
    return (
      <KeyboardAvoidingView
        style={{ flex: 1 }}
        keyboardVerticalOffset={90}
        behavior="padding"
      >
        {this.renderContent()}
      </KeyboardAvoidingView>
    );
  }
}

// Moved here for debugging for now

//  // Network request to our API to get an OAuth token
//  async getLinkedInAuthURL() {
//   console.log('getting linkedin auth info');
//   this.setState({ loading: true });
//   console.log('sending fetch request');
//   const result = await fetchAuth(endpoints.linkedInLogin);

//   if (result.error) {
//     showFlashErrorMessage(result.error);
//     return null;
//   }
//   return result;
// }

// async getLinkedInData(linkedInAuthData) {
//   try {
//     const result = await fetchAuth(endpoints.retrieveLinkedInInfo(toQueryString(linkedInAuthData)));
//     if (result.error) {
//       showFlashErrorMessage(result.error);
//     } else {
//       //this call will be altered once we gefull linkedin partner api access
//       //this.setState({ profileInfo: result, loading: false });
//     }
//   } catch (error) {
//     showFlashErrorMessage(error);
//     this.setState({ loading: false });
//   }
// }

// // Navigates to a LinkedIn webview modal, when the auth creds are fetched successfully it will execute onSuccess
// async openLinkedInWebView() {
//   console.log('linkedWebview Func hit');
//   this.setState({ loading: true });

//   try {
//     const result = await this.getLinkedInAuthURL();
//     this.setState({ loading: false });
//     console.log('navigating to linkedin webview');
//     this.props.navigation.navigate('linkedInWebView', { result, onSuccess: this.getLinkedInData });
//   } catch (error) {
//     showFlashErrorMessage(error);
//     this.setState({ loading: false });
//   }
// }
