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

import { FormLabel, Spacer } from '../../components/common';
import { fetchAuth } from '../../utils/fetch';
import { strings } from '../../locales/i18n';
import { showFlashErrorMessage } from '../../utils/errorHandler';
import { isEmail } from '../../utils/aux';

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 ForgotPasswordScreen extends React.Component {
  static navigationOptions = {
    header: null
  }

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

  /**
   * Send an API request and display error/sucess message
   */
  onRequestResetPress() {
    Keyboard.dismiss();
    this.setState({ loading: true });
    const body = { email: this.state.email };

    fetchAuth(endpoints.passwordReset, body).then(res => {
      this.setState({ loading: false });
      if (res.error) {
        showFlashErrorMessage(res.error);
      } else {
        this.showSuccessMessage();
      }
    }).catch(() => {
      this.setState({ loading: false });
      showFlashErrorMessage(errors.APP);
    });
  }

  /**
   * Displays a success message
   */
  showSuccessMessage() {
    showMessage({
      message: 'Password reset link sent',
      description: 'Please check your email.',
      type: 'success',
      icon: 'auto',
      autoHide: false,
      onPress: () => this.props.navigation.navigate('login')
    });
  }

  renderContent() {
    return (
      <TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
        <View style={{ flex: 1 }}>
          
          {/* LOGO */}
          <View style={styles.logoContainerStyle}>
            <Image source={logo} />
          </View>

          {/* HEADER */}
          <View>
            <Text style={styles.headerStyle} >Forgot your password?</Text>
            <Text style={styles.instructions}>Enter your email address below and we'll get you back on track</Text>
          </View>

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

          {/* BUTTONS */}
          <View>
            <Text onPress={() => this.props.navigation.navigate('login')} style={styles.backButtonStyle} > 
              Back to Login
            </Text>

            <Button
              onPress={this.onRequestResetPress.bind(this)}
              title={strings('settings.forgotPasswordScreen.submitButton')}
              buttonStyle={styles.buttonStyle}
              disabled={!isEmail(this.state.email) || this.state.loading}
              loading={this.state.loading}
              fontSize={20}
            />
          </View>
        </View>
      </TouchableWithoutFeedback>
    );
  }

  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 = {
  logoContainerStyle: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: 50,
    marginBottom: 40
  },
  logoStyle: {
    width: '100%',
    height: '100%'
  },
  headerStyle: {
    color: colors.headerBlue,
    fontWeight: 'bold',
    marginLeft: 20,
    fontSize: 24
  },
  instructions: {
    color: colors.grey,
    fontSize: 18,
    marginLeft: 20,
    marginRight: 20
  },
  buttonStyle: {
    width: SCREEN_WIDTH * 0.9,
    marginTop: 15,
    marginBottom: 30,
    borderRadius: 5,
    backgroundColor: colors.buttonBlue
  },
  backButtonStyle: {
    marginLeft: 20,
    fontSize: 18,
    color: colors.grey
  }, 
  labelStyle: {
    color: colors.labelBlue
  },
  inputTextStyle: {
    color: colors.black
  }
};
