import React from 'react';
import { Dimensions, KeyboardAvoidingView, Platform, ScrollView, Text, View, TouchableOpacity } 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: '',
      loading: false
    };
  }

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

  async onResendPress() {
    this.setState({ loading: true });
    const phoneNumber = this.props.navigation.state.params.phoneNumber;
    const resp = await fetchAuth(endpoints.sendCode, { phoneNumber });
    this.setState({ loading: false });
    
    if (resp.error) {
      showFlashErrorMessage(resp.error);
    }
  }

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

  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>

          {/* HELP BUTTONS */}
          <View style={{ marginTop: 25 }}>
            <TouchableOpacity onPress={() => this.props.navigation.goBack()}>
              <Text style={styles.textButtonStyle}>Wrong Number?</Text>
            </TouchableOpacity>
            <TouchableOpacity onPress={() => this.onResendPress()}>
              <Text style={styles.textButtonStyle}>Resend code?</Text>
            </TouchableOpacity>
          </View>
        </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 }
  },
  textButtonStyle: {
    color: colors.darkBlue,
    fontSize: 16,
    fontWeight: 'bold',
    marginLeft: 20,
    marginBottom: 20
  }
};
