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

import { FormLabel, Spacer, TextButton } from '../../components/common';
import { strings } from '../../locales/i18n';
import { fetchAuth } from '../../utils/fetch';
import { showFlashErrorMessage } from '../../utils/errorHandler';
import { saveAuthState } from '../../realm/actions/AuthActions';

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

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

  constructor(props) {
    super(props);
    this.state = {
      id: '',
      password: '',
      loading: false
    };
  }

  async onLoginPress() {
    Keyboard.dismiss();
    this.setState({ loading: true });
    const body = this.getLoginRequestBody();
    const resp = await fetchAuth(endpoints.login, body);
    this.setState({ loading: false });

    if (resp.error) {
      this.clearInvalidInputField(resp.error);
      showFlashErrorMessage(resp.error);
    } else {
      saveAuthState(resp.sessionId);
      this.props.navigation.navigate('App');
    }
  }

  // Creates the body of the request from the current state; determines if the identifier is an email or a tagferId.
  getLoginRequestBody() {
    const body = { password: this.state.password };
    if (this.state.id.indexOf('@') !== -1) {
      body.email = this.state.id;
    } else {
      body.tagferId = this.state.id;
    }
    return body;
  }

  clearInvalidInputField(error) {
    if (error === errors.AUTH_USER_NOT_FOUND) {
      this.setState({ id: '' });
    } else if (error === errors.AUTH_WRONG_PASSWORD) {
      this.setState({ password: '' });
    }
  }

  /**
   * Validation for the disbaling the button, if the there is id or password is less than 6.
   */
  isButtonDiabled() {
    return this.state.id.length < 1 || this.state.password.length < 6 || this.state.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 */}
          <View>
            <Text style={styles.headerStyle} >Login</Text>
          </View>
          {/* TEXT INPUTS */}
          <View style={{ flex: 3 }}>
            <Spacer />
            <FormLabel 
              labelText={strings('common.contactFields.email_or_tagferid_label')} 
              textStyle={styles.labelStyle}
            />
            <FormInput
              value={this.state.id}
              onChangeText={id => this.setState({ id })}
              placeholder={strings('common.contactFields.email_or_tagferid_placeholder')}
              autoCorrect={false}
              autoCapitalize='none'
              inputStyle={styles.inputTextStyle}
            />
            <Spacer />

            <FormLabel 
              labelText={strings('userLoginScreen.password')}
              textStyle={styles.labelStyle}
            />
            <PasswordField 
              value={this.state.password} 
              onChangeText={password => this.setState({ password })} 
              inputStyle={styles.inputTextStyle}
              visible={this.state.passwordVisible}
              onEyePress={() => this.setState({ passwordVisible: !this.state.passwordVisible })}
            />
            <Spacer />
            {/* FORGOT PASSWORD OR SIGNUP */}
            <View>
              <TextButton
                leftText={strings('userLoginScreen.forgotPasswordText')}
                rightText={strings('userLoginScreen.forgotPasswordButton')}
                onPress={() => this.props.navigation.navigate('forgotPassword')}
                disabled={this.state.loading}
              />

              <TextButton
                leftText={strings('userLoginScreen.userCreateText')}
                rightText={strings('userLoginScreen.userCreateButton')}
                onPress={() => this.props.navigation.navigate('signup1')}
                disabled={this.state.loading}
              />
            </View>
          </View>
        </View>

        <Button
          onPress={this.onLoginPress.bind(this)}
          title={strings('userLoginScreen.loginButton')}
          buttonStyle={styles.buttonStyle}
          loading={this.state.loading}
          disabled={this.isButtonDiabled()}
          fontSize={20}
        />

      </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: 20,
    fontSize: 24
  },
  logoContainerStyle: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: 50
  },
  logoStyle: {
    width: '100%',
    height: '100%'
  },
  labelStyle: {
    color: colors.labelBlue
  },
  buttonStyle: {
    width: SCREEN_WIDTH * 0.9,
    marginTop: 15,
    marginBottom: 30,
    borderRadius: 5,
    backgroundColor: colors.buttonBlue
  },
  inputTextStyle: {
    color: colors.black
  }
};
