import React from 'react';
import { Keyboard, Dimensions, KeyboardAvoidingView, Platform, ScrollView, Text, View } from 'react-native';
import { Button, FormInput, FormValidationMessage } from 'react-native-elements';

import { FormLabel } from '../../components/common';
import { strings } from '../../locales/i18n';
import { isEmpty } from '../../utils/aux';
import { getErrorObject, showFlashErrorMessage } from '../../utils/errorHandler';
import { loadSignupState, saveSignupState } from '../../realm/actions/AuthActions';
import { fetchAuth } from '../../utils/fetch';

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

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

  constructor(props) {
    super(props);
    this.state = {
      tagferId: '',
      error: '',
      loading: false,
      twitterDisabled: false,
      twitterUsername: false
    };

    loadSignupState(2).then(result => {
      this.isUpdate = result.isUpdate;
      this.setState({ ...result.prevState });
    });
    this.keyboardDidHide = this.keyboardDidHide.bind(this);
    this.onChangeText = this.onChangeText.bind(this);
    this.openTwitterWebView = this.openTwitterWebView.bind(this);
    this.setTwitterUsername = this.setTwitterUsername.bind(this);
    this.removeTwitterUsername = this.removeTwitterUsername.bind(this);
  }

  componentDidMount() {
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this.keyboardDidHide);
  }

  componentWillUnmount() {
    this.keyboardDidHideListener.remove();
  }

  // Poulates the state.error dynmically if there are errors as the user types.
  onChangeText(tagferId) {
    let error = '';
    if (tagferId.indexOf('@') !== -1) {
      error = 'Tagfer ID cannot contain @';
      this.input.shake();
    }

    this.setState({ tagferId, twitterDisabled: true, error });
  }

  async onSaveButtonPress() {
    Keyboard.dismiss();
    this.setState({ loading: true });

    const tagferId = this.state.tagferId;
    const resp = await fetchAuth(endpoints.tagferIdExists(tagferId));
    this.setState({ loading: false });

    if (resp.error) {
      showFlashErrorMessage(resp.error);
    } else if (resp.result === true) {
      this.input.shake();
      const errorObject = getErrorObject(errors.AUTH_UID_ALREADY_EXISTS);
      this.setState({ error: errorObject.desc });
    } else {
      this.props.navigation.navigate('signup3a');
      saveSignupState(2, this.state, this.isUpdate);
    }
  }

  // Wrapper to set the tagferId to the twitter username
  setTwitterUsername(username) {
    this.input.blur();
    this.setState({ tagferId: username, twitterUsername: true });
  }
  
  // Network request to our API to get an OAuth token
  async getTwitterAuthURL() {
    this.setState({ loading: true });
    const twitter = { authenticate: 'https://api.twitter.com/oauth/authenticate' };
    const resp = await fetchAuth(endpoints.twitterToken);
    this.setState({ loading: false });
    
    if (resp.error) { throw resp.error; }
      
    return `${twitter.authenticate}?oauth_token=${resp.token}`;
  }

  // Navigates to a twitter webview modal, when the username is fetched successfully it will execute onSuccess
  async openTwitterWebView() {
    this.setState({ loading: true, error: '' });

    try {
      const url = await this.getTwitterAuthURL();
      this.setState({ loading: false });
      this.props.navigation.navigate('twitterWebView', { url, onSuccess: this.setTwitterUsername });
    } catch (error) {
      this.setState({ error, loading: false });
    }
  }

  // Disables the twitter button to minimize distraction for UX
  keyboardDidHide() {
    this.setState({ twitterDisabled: false });
  }

  // Button is diabled if there is no tagferId or there is an error
  isButtonDisabled() {
    return isEmpty(this.state.tagferId) || !isEmpty(this.state.error) || this.state.loading;
  }

  // Disbaled if user is typing or we are during a request
  isTwitterDisabled() {
    return this.state.twitterDisabled || this.state.loading;
  }

  removeTwitterUsername() {
    this.setState({ tagferId: '', twitterUsername: false });
  }

  renderTwitterButtons() {
    if (this.state.twitterUsername) {
      return (
        <Button
          onPress={this.removeTwitterUsername}
          title={this.state.tagferId}
          buttonStyle={styles.twitterUsernameButtonStyle}
          fontSize={17}
          textStyle={{ color: colors.headerBlue }}
          disabled={this.isTwitterDisabled()}
          icon={styles.twitterIconStyle('#1DA1F2')}
          iconRight={{ name: 'close', color: colors.headerBlue }}
        />
      );
    }
    return (
      <Button
        onPress={this.openTwitterWebView}
        title={strings('userCreateFlow.createTagferId.twitterButton')}
        buttonStyle={styles.twitterButtonStyle}
        fontSize={15}
        disabled={this.isTwitterDisabled()}
        icon={styles.twitterIconStyle(colors.white)}
      />);
  }

  renderContent() {
    return (
      <ScrollView contentContainerStyle={{ flexGrow: 1, backgroundColor: colors.white }} keyboardShouldPersistTaps="handled">
        <View style={{ flex: 1 }}>
          {/* INSTRUCTIONS */}
          <Text style={styles.instructions}>{strings('userCreateFlow.createTagferId.explanation')}</Text>

          {/* TEXT INPUT */}
          <FormLabel 
            labelText={strings('common.contactFields.tagferId_labelText')}
            textStyle={styles.labelStyle}
          />
        
          <FormInput
            value={this.state.tagferId}
            onChangeText={this.onChangeText}
            placeholder={strings('userCreateFlow.createTagferId.tagferIdField_description')}
            autoCorrect={false}
            autoCapitalize='none'
            inputStyle={styles.inputTextStyle}
            editable={!this.state.twitterUsername}
            ref={ref => (this.input = ref)}
          />

          <View style={styles.formValidationStyle}>
            <FormValidationMessage>{this.state.error}</FormValidationMessage>
          </View>
          
          {/* EXAMPLES */}
          <Text style={styles.examplesStyle}>{strings('userCreateFlow.createTagferId.tagferIDExamples')}</Text>

          {/* TWITTER BUTTON */}
          <View style={styles.twitterTextContainerStyle}>
            <Text style={styles.twitterTextStyle}>{strings('userCreateFlow.createTagferId.wantTwitter')}</Text>
          </View>

          <View style={styles.twitterButtonContainerStyle}>
            {this.renderTwitterButtons()}
          </View>

        </View>

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

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

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

const SCREEN_WIDTH = Dimensions.get('window').width;

const styles = {
  instructions: {
    left: 20,
    width: '90%',
    marginTop: 20,
    marginBottom: 30,
    fontSize: 16,
    color: colors.grey,
    textAlign: 'justify'
  },
  formValidationStyle: {
    width: '100%', 
    alignItems: 'flex-end',
    marginBottom: 0 
  },
  buttonStyle: {
    width: SCREEN_WIDTH * 0.9,
    marginTop: 15,
    marginBottom: 30,
    borderRadius: 5,
    backgroundColor: colors.buttonBlue
  },
  chevronIconStyle: {
    name: 'chevron-right', 
    color: colors.white,
    size: 30,
    style: { marginLeft: 0 }
  },
  twitterTextContainerStyle: { 
    marginTop: 50,
    marginLeft: 30,
    marginRight: 30
  },
  twitterTextStyle: {
    fontSize: 17,
    textAlign: 'center',
    color: colors.black
  },
  twitterButtonContainerStyle: {
    marginTop: 15,
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center'
  },
  twitterButtonStyle: {
    width: SCREEN_WIDTH * 0.85,
    height: 50,
    borderRadius: 25,
    backgroundColor: '#1DA1F2'
  },
  twitterUsernameButtonStyle: {
    alignSelf: 'flex-start',
    height: 50,
    borderRadius: 25,
    backgroundColor: colors.offWhite
  },
  twitterIconStyle: (color) => ({
    name: 'twitter',
    type: 'font-awesome',
    size: 25,
    color
  }),
  inputTextStyle: {
    color: colors.black
  },
  examplesStyle: {
    left: 20,
    width: '90%',
    marginTop: 0,
    fontSize: 16,
    color: colors.grey,
    textAlign: 'justify',
  },
  freeCenteredTextStyle: {
    textAlign: 'center',
    fontSize: 17
  },
  labelStyle: {
    color: colors.labelBlue
  }
};
