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 CountryPicker from 'react-native-country-picker-modal';

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

import colors from '../../config/colors.json';
import endpoints from '../../config/apiEndpoints';
import { loadSignupState, saveSignupState } from '../../realm/actions/AuthActions';


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

  constructor(props) {
    super(props);
    this.state = {
      phoneNumber: '',
      cca2: 'US',
      callingCode: '1',
      loading: false
    };
    loadSignupState(3).then(result => {
      this.setState({ ...result.prevState });
      this.isUpdate = result.isUpdate;
    });
  }

  // Reformat the masked number and send the request
  async onSaveButtonPress() {
    this.setState({ loading: true });
    const phoneNumber = `+${this.state.callingCode}${this.input.getRawValue()}`;
    const resp = await fetchAuth(endpoints.sendCode, { phoneNumber });
    this.setState({ loading: false });

    if (resp.error) {
      showFlashErrorMessage(resp.error);
    } else { 
      this.props.navigation.navigate('signup3b', { phoneNumber });
      saveSignupState(3, { ...this.state, formattedPhoneNumber: phoneNumber }, this.isUpdate);
    } 
  }

  // 14 chars include mask |(999) 999-9999|, its actually 10
  isDisabled() {
    return this.state.phoneNumber.length < 14 || this.state.loading;
  }

  renderContent() {
    return (
      <ScrollView contentContainerStyle={{ flexGrow: 1, backgroundColor: colors.white }} keyboardShouldPersistTaps="handled">
        <View style={{ flex: 1 }}>
          {/* INSTRUCTIONS */}
          <Text style={styles.instructions}>{strings('userCreateFlow.phoneAdd.description')}</Text>
          
          <View style={{ flexDirection: 'row', marginLeft: 20 }}>
            {/* COUNTRY FLAG */}
            <CountryPicker
              closeable
              filterable
              onChange={(country) => this.setState({ ...country })}
              cca2={this.state.cca2}
              translation='eng'
              styles={{ itemCountryName: { borderBottomWidth: 0 } }}

            />
            {/* CALLING CODE */}
            <Text style={styles.callingCodeText}>+{this.state.callingCode}</Text> 

            {/* PHONE NUMBER */}
            <TextInputMask
                ref={ref => (this.input = ref)}
                value={this.state.phoneNumber}
                underlineColorAndroid={'transparent'}
                autoCapitalize={'none'}
                autoCorrect={false}
                onChangeText={(phoneNumber) => this.setState({ phoneNumber })}
                placeholder={'Phone Number'}
                keyboardType={Platform.OS === 'ios' ? 'number-pad' : 'numeric'}
                style={styles.textInput}
                type={'cel-phone'}
                options={{ withDDD: true, dddMask: '(999) 999-9999' }}
                autoFocus
            />
          </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: {
    padding: 0,
    margin: 0,
    flex: 1,
    fontSize: 20
  },
  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 }
  }
};
