import React from 'react';
import { Dimensions, KeyboardAvoidingView, Platform, ScrollView, Text, View } from 'react-native';
import { Button } from 'react-native-elements';
import { TextInputMask } from 'react-native-masked-text';

import { strings } from '../../locales/i18n';
import { showFlashErrorMessage } from '../../utils/errorHandler';
import { fetchAuth } from '../../utils/fetch';

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


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

  constructor(props) {
    super(props);
    this.state = {
      code: ''
    };
  }

  // Reformat the masked code and send the request
  onSaveButtonPress() {
    this.setState({ loading: true });
    const phoneNumber = this.props.navigation.state.params.phoneNumber;
    const code = this.input.getRawValue();
    fetchAuth(endpoints.verifyCode, { phoneNumber, code }).then(res => { 
      if (res.error) {
        showFlashErrorMessage(res.error);
      } else if (res.result === false) {
        showFlashErrorMessage(errors.AUTH_VERIFICATION_CODE_MISMATCH); 
      } else {
        this.props.navigation.navigate('signup4');
      }
    }).catch(() => showFlashErrorMessage(errors.APP_NETWORK_ERROR))
    .finally(() => this.setState({ loading: false }));
  }

  isDisabled() {
    return this.state.code.length !== 7;
  }

  renderContent() {
    const phoneNumber = this.props.navigation.state.params.phoneNumber;

    return (
      <ScrollView contentContainerStyle={{ flexGrow: 1, backgroundColor: colors.white }} keyboardShouldPersistTaps="handled">
        <View style={{ flex: 1 }}>
          {/* INSTRUCTIONS */}
          <Text style={styles.instructions}>{strings('userCreateFlow.phoneVerify.description', { phoneNumber })}</Text>
          
          <View style={{ flexDirection: 'row', justifyContent: 'center' }}>

            {/* CODE */}
            <TextInputMask
                ref={ref => (this.input = ref)}
                value={this.state.code}
                underlineColorAndroid={'transparent'}
                autoCapitalize={'none'}
                autoCorrect={false}
                onChangeText={(code) => this.setState({ code })}
                placeholder={'_ _ _   _ _ _'}
                keyboardType={Platform.OS === 'ios' ? 'number-pad' : 'numeric'}
                style={styles.textInput}
                type={'cel-phone'}
                options={{ withDDD: true, dddMask: '999 999' }}
                autoFocus
                maxLength={7}
            />
          </View>

          <Text style={styles.wrongNumberButtonStyle} onPress={() => this.props.navigation.goBack()}>Wrong Number?</Text>

        </View>


        {/* SAVE AND CONTINUE BUTTON */}
        <Button
          onPress={this.onSaveButtonPress.bind(this)}
          title={strings('common.buttons.saveAndContinue')}
          buttonStyle={styles.buttonStyle}
          disabled={this.isDisabled()}
          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'
  },
  countryPicker: {
    alignItems: 'center',
    justifyContent: 'center'
  },
  callingCodeView: {
    alignItems: 'center',
    justifyContent: 'center'
  },
  callingCodeText: {
    fontSize: 20,
    paddingRight: 10,
    paddingLeft: 10
  },
  textInput: {
    margin: 0,
    fontSize: 38
  },
  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 }
  },
  wrongNumberButtonStyle: {
    color: colors.darkBlue,
    fontSize: 15,
    fontWeight: 'bold',
    marginLeft: 20,
    marginTop: 20
  }
};
