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

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

import PasswordField from '../../components/new/PasswordField';
import logo from '../../../assets/logo-round.png';
import colors from '../../config/colors.json';
import endpoints from '../../config/apiEndpoints';
import errors from '../../config/errors';


export default class SignupScreenOne extends React.Component {
  static navigationOptions = {
    header: null
  }

  constructor(props) {
    super(props);
    this.state = {
      firstName: '',
      lastName: '',
      email: '',
      password: '',
      loading: false,
      error: '',
      passwordVisible: false
    };

    loadSignupState(1).then(result => {
      this.setState({ ...result.prevState });
      this.isUpdate = result.isUpdate;
    });
  }
  
  // Saves the current information locally and handles error processing
  async onSaveButtonPress() {
    Keyboard.dismiss();
    this.setState({ loading: true });

    const resp = await fetchAuth(endpoints.emailExists(this.state.email));
    this.setState({ loading: false });
    
    if (resp.error) {
      showFlashErrorMessage(resp.error);
    } else if (resp.result === true) {
      this.input.shake();
      const errorObject = getErrorObject(errors.AUTH_EMAIL_ALREADY_EXISTS);
      this.setState({ error: errorObject.desc });
    } else {
      this.props.navigation.navigate('signup2');
      saveSignupState(1, this.state, this.isUpdate);
    }
  }

  /**
   * Boolean function that says if the button is disabled based on if the fields are empty.
   */
  isButtonDisabled() {
    const { firstName, lastName, email, password, error, loading } = this.state;
    return isEmpty(firstName) || isEmpty(lastName) || !isEmail(email) || password.length < 6 || !isEmpty(error) || loading;
  }

  renderContent() {
    return (
      <ScrollView contentContainerStyle={{ flexGrow: 1, backgroundColor: colors.white }} keyboardShouldPersistTaps="handled" >
        <View style={{ flex: 1 }}>
          {/* LOGO */}
          <View style={styles.logoContainerStyle}>
            <Image source={logo} />
          </View>

          {/* HEADER */}
          <Text style={styles.headerStyle} >Signup</Text>

          {/* TEXT INPUTS */}
          <View style={{ flex: 3 }}>
            <Spacer />
            <FormLabel
              labelText={strings('common.contactFields.firstName_labelText')}
              textStyle={styles.labelStyle}
            />
            <FormInput
              value={this.state.firstName}
              onChangeText={firstName => this.setState({ firstName })}
              placeholder={strings('common.contactFields.firstName_placeholder')}
              autoCorrect={false}
              autoCapitalize='words'
              inputStyle={styles.inputTextStyle}
            />
            <Spacer />

            <FormLabel 
              labelText={strings('common.contactFields.lastName_labelText')}
              textStyle={styles.labelStyle}
            />
            <FormInput
              value={this.state.lastName}
              onChangeText={lastName => this.setState({ lastName })}
              placeholder={strings('common.contactFields.lastName_placeholder')}
              autoCorrect={false}
              autoCapitalize='words'
              inputStyle={styles.inputTextStyle}
            />
            <Spacer />

            <FormLabel 
              labelText={strings('common.contactFields.email_labelText')}
              textStyle={styles.labelStyle}
            />
            <FormInput
              value={this.state.email}
              onChangeText={email => this.setState({ email, error: '' })}
              placeholder={strings('common.contactFields.email_or_tagferid_placeholder')}
              autoCorrect={false}
              autoCapitalize='none'
              inputStyle={styles.inputTextStyle}
              ref={ref => (this.input = ref)}
            />
            <View style={styles.formValidationStyle}>
              <FormValidationMessage>{this.state.error}</FormValidationMessage>
            </View>

            <FormLabel
              labelText={strings('userCreateFlow.signUp.password')}
              textStyle={styles.labelStyle}
              containerStyle={{ marginTop: 0 }}
            />
            <PasswordField 
              value={this.state.password} 
              onChangeText={password => this.setState({ password })} 
              inputStyle={styles.inputTextStyle}
              visible={this.state.passwordVisible}
              onEyePress={() => this.setState({ passwordVisible: !this.state.passwordVisible })}
            />

            {/* TERMS AND CONDITIONS */}
            <View style={{ marginTop: 35 }}>
              <Text style={styles.freeTextStyle}>
                {strings('userCreateFlow.termsLeft')}
              </Text>
              <Text style={styles.termsButtonStyle} onPress={() => this.props.navigation.navigate('termsAndConditions')}>
                {strings('userCreateFlow.termsRight')}
              </Text>
            </View>
          </View>

          <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}
          />
        </View>
      </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 = {
  headerStyle: {
    color: colors.headerBlue,
    fontWeight: 'bold',
    marginLeft: 15,
    fontSize: 24
  },
  logoContainerStyle: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: 50
  },
  logoStyle: {
    width: '100%',
    height: '100%'
  },
  buttonStyle: {
    width: SCREEN_WIDTH * 0.9,
    marginTop: 5,
    marginBottom: 30,
    borderRadius: 5,
    backgroundColor: colors.buttonBlue
  },
  chevronIconStyle: {
    name: 'chevron-right', 
    color: colors.white,
    size: 30,
    style: { marginLeft: 0 }
  },
  inputTextStyle: {
    color: colors.black
  },
  formValidationStyle: {
    width: '100%', 
    alignItems: 'flex-end',
    marginBottom: 0 
  },
  freeTextStyle: {
    marginLeft: 20,
    fontSize: 18,
    color: '#111111'
  },
  termsButtonStyle: {
    fontSize: 18,
    color: colors.grey,
    marginLeft: 20,
    fontWeight: 'bold'
  },
  labelStyle: {
    color: colors.labelBlue
  }
};
