import React, {Component} from 'react';
import {
  View,
  Text,
  TouchableHighlight,
  StyleSheet,
  TouchableOpacity,
  Keyboard,
  Linking,
  TextInput,
} from 'react-native';
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view';
import NaviBar from '../../components/navi-bar';
import {scale, verticalScale, moderateScale} from 'react-native-size-matters';
import LoadingView from '../../common/loading';
import Icon from 'react-native-vector-icons/FontAwesome5';
import {Dropdown} from 'react-native-material-dropdown';
import {colors} from '../../assets/styles/colors-theme';
import {Fonts} from '../../assets/styles/fonts-theme';
import BackHeader from '../../components/backHeader';
import Toast, {DURATION} from 'react-native-easy-toast';
import CommonTextInput from '../../components/commonTextInput';
import {inject, observer} from 'mobx-react';
import {observable} from 'mobx';
import {width, height} from '../../common/screen';
import Size from '../../common/size';
const size = new Size();
const countryCodeDropDownData = [
  {value: '852', label: '+852'},
  {value: '86', label: '+86'},
  {value: '886', label: '+886'},
];

@inject('appStore')
@observer
export default class SignUpVerify extends Component {
  @observable
  phoneVerification = '';
  @observable
  signupData = {};
  @observable
  sendstate = true;
  @observable
  countryCode = '852';
  @observable
  thirdParty = false;

  constructor(props) {
    super(props);
    this.store = props.appStore;
    this.state = {
      countryCode: '852',
    };
    console.log(this.props.navigation.getParam('type', false));
  }
  componentWillMount() {
    this.signupData = this.props.navigation.state.params.signupData;
    this.thirdParty = this.signupData.thirdParty;
    delete this.signupData.thirdParty;
  }

  navigatieAction(page) {
    this.props.navigation.navigate(page);
  }

  startToCount() {
    this.interval = setInterval(() => {
      this.count();
    }, 1000);
  }
  resendAction() {
    this.store.countdown = 10;
    this.resend = false;
    this.startToCount();
  }

  count() {
    this.store.timer -= 1;
    if (this.store.timer == 0) {
      this.sendstate = true;
      clearInterval(this.interval);
    }
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  handleClickCountdown() {
    var bodyFormData = new FormData();

    bodyFormData.append('country_code', '852');
    bodyFormData.append('phone_number', this.signupData.phone.toString());

    this.store.sendsmsVerify(bodyFormData, this);
  }

  startToCountDown = () => {
    this.countdown && this.countdown.startCountdown();
  };

  handleNetworkFailed = () => alert('network failed');

  sendTextReturn() {
    if (this.sendstate) {
      return this.store.text.send;
    } else {
      return this.store.timer.toString();
    }
  }

  sendAction() {
    if (this.sendstate) {
      if (this.signupData.phone.length > 6) {
        this.handleClickCountdown();
        clearInterval(this.interval);
        this.store.timer = 60;
        this.sendstate = false;
        this.startToCount();
      } else {
        this.refs.toast.show(this.store.text.Please_input_phone_number);
      }
    }
  }

  signupAction() {
    if (this.signupData.vercode != '') {
      if (this.props.navigation.state.params.addphone) {
        if (this.signupData.phone != '') {
          var data = {
            phone: this.signupData.phone,
            countryCode: this.signupData.countryCode,
            vercode: this.signupData.vercode,
          };
          this.store.bindPhone(data, this);
        } else {
          this.refs.toast.show(this.store.text.Please_input_phone_number);
        }
      } else {
        this.store.signupPost(this, this.signupData);
      }
    } else {
      this.refs.toast.show('Please input verification code');
    }
  }

  handleStopCountdown = () => this.countdown && this.countdown.stopCountdown();

  countDownButton() {
    return (
      <View style={{flex: 1}}>
        {/* <Countdown
          ref={r => (this.countdown = r)}
          time={60}
          onPress={this.handleClickCountdown}
         // onNetworkFailed={this.handleNetworkFailed}
          onDidFinishCountdown={this.handleCountdownOver}
        >
          {({ status, time }) => {
            let title, containerStyle, titleStyle;
            switch (status) {
              case CountdownStatus.Idle:
                title = "send";
                containerStyle = styles.countdown;
                titleStyle = styles.countdownTitle;
                break;
              case CountdownStatus.Counting:
                title = `sent(${time})`;
                containerStyle = styles.countdown;
                titleStyle = styles.countdownTitle;
                break;
              case CountdownStatus.Over:
                title = "resend";
                containerStyle = styles.countdown;
                titleStyle = styles.countdownTitle;
                break;
            }
            return (
              <View style={containerStyle}>
                <Text style={titleStyle}>{title}</Text>
              </View>
            );
          }}
        </Countdown> */}
      </View>
    );
  }

  render() {
    return (
      <View style={{flex: 1, backgroundColor: 'white'}}>
        <LoadingView visible={this.store.loading} />
        {/* <View style={{ flex: 0.07, backgroundColor: colors.mainColor, justifyContent: 'center', }}>
                    <Icon name={'arrow-left'}
                        size={22}
                        color={'white'}
                        style={{ marginLeft: 20 }} />

                </View> */}
        <BackHeader instance={this} back={true} title={'電話認證'} />

        <View style={{flex: 1, width: width, marginTop: 10}}>
          <KeyboardAwareScrollView>
            <View style={{flex: 1, alignItems: 'center'}}>
              <Icon
                style={{marginTop: 20}}
                name={'envelope-open-text'}
                color={colors.mainColor}
                size={100}
              />
              <Text
                style={{
                  margin: 30,
                  fontSize: 15,
                  color: colors.textColor,
                  textAlign: 'center',
                }}>
                {this.store.text.verificarionAlart}
              </Text>
              {/* <View
              style={{
                borderBottomColor: colors.textColor,
                borderBottomWidth: 1,
                flexDirection: 'row',
                marginLeft: 30,
                marginRight: 30,
                marginTop: 20,
                height: verticalScale(40),
                borderRadius: 5,
              }}>

                
              <Text
                style={{
                  // backgroundColor:theme.inputBgc,
                  color: colors.textColor,
                  height: verticalScale(35),
                  // marginBottom: moderateScale(15),
                  paddingBottom: 0,
                  fontSize: 13,
                  paddingRight: 10,
                  paddingLeft: 20,
                  fontFamily: Fonts.ubuntuL,
                }}>
                {this.store.text.phonenumber +
                  ': ' +
                  this.signupData.countryCode +
                  ' ' +
                  this.signupData.phone}
              </Text>
            </View> */}
              {this.thirdParty ? (
                <View
                  style={{
                    borderBottomColor: colors.textColor,
                    borderBottomWidth: 1,
                    flexDirection: 'row',
                    marginLeft: 30,
                    marginRight: 30,
                    marginTop: 20,
                    height: verticalScale(40),
                    borderRadius: 5,
                  }}>
                  <Dropdown
                    label=""
                    data={countryCodeDropDownData}
                    labelFontSize={0}
                    fontSize={12}
                    dropdownOffset={{top: 0, bottom: 0}}
                    value={this.countryCode}
                    onChangeText={value => {
                      this.signupData.countryCode = value;
                      console.log(this.countryCode);
                    }}
                    textColor={colors.mainColor}
                    itemTextStyle={{fontFamily: Fonts.ubuntu}}
                    baseColor={colors.baseColor}
                    containerStyle={{
                      borderWidth: 1,
                      borderRadius: 6,
                      borderColor: colors.textColor,
                      margin: 0,
                      padding: 0,
                      width: 70,
                      height: 25,
                      marginTop: 7,
                    }}
                    style={{fontFamily: Fonts.ubuntu, color: colors.mainColor}}
                    inputContainerStyle={{
                      borderBottomColor: 'transparent',
                      marginBottom: scale(-12),
                      marginLeft: 10,
                    }}
                    labelHeight={0}
                  />
                  <TextInput
                    style={{
                      // backgroundColor:theme.inputBgc,
                      flex: 1,
                      color: colors.textColor,
                      height: verticalScale(35),
                      marginBottom: moderateScale(30),
                      paddingBottom: 0,
                      fontSize: 13,
                      paddingRight: 20,
                      paddingLeft: 20,
                      fontFamily: Fonts.ubuntuL,
                    }}
                    value={this.signupData.phone}
                    underlineColorAndroid="rgba(0,0,0,0)"
                    onChangeText={phone => (this.signupData.phone = phone)}
                    placeholder={this.store.text.phonenumber}
                    placeholderStyle={{fontWeight: 'bold'}}
                    placeholderTextColor={colors.textColor}
                    secureTextEntry={false}
                    blurOnSubmit={false}
                    returnKeyType={'next'}
                    onSubmitEditing={event => {
                      this.nameinput.focus();
                    }}
                  />
                </View>
              ) : (
                <Text
                  style={{
                    // backgroundColor:theme.inputBgc,
                    color: colors.mainColor,
                    height: verticalScale(35),
                    // marginBottom: moderateScale(15),
                    paddingBottom: 0,
                    fontSize: 30,
                    fontFamily: Fonts.ubuntuL,
                  }}>
                  {'+' +
                    this.signupData.countryCode +
                    ' ' +
                    this.signupData.phone}
                </Text>
              )}

              <TouchableOpacity
                onPress={() => {
                  this.sendAction();
                }}
                style={{
                  width: 100,
                  height: 50,
                  marginTop: 20,
                  borderRadius: 10,
                  backgroundColor: colors.mainColor,
                  justifyContent: 'center',
                  alignItems: 'center',
                }}>
                <Text style={{color: 'white', fontFamily: Fonts.ubuntu}}>
                  {this.sendTextReturn()}
                </Text>
              </TouchableOpacity>

              <View
                style={{
                  marginLeft: 20,
                  marginRight: 20,
                  marginTop: 30,
                  flexDirection: 'row',
                  justifyContent: 'space-between',
                }}>
                <View
                  style={{
                    backgroundColor: colors.inputBgc,
                    marginLeft: 10,
                    alignItems: 'center',
                    justifyContent: 'center',
                    height: verticalScale(40),
                    borderRadius: 12,
                    width: 200,
                  }}>
                  <TextInput
                    style={{
                      color: colors.mainColor,
                      fontSize: 15,
                      paddingRight: 40,
                      paddingLeft: 40,
                      fontFamily: Fonts.ubuntuL,
                      alignSelf: 'stretch',
                      textAlign: 'center',
                    }}
                    onChangeText={text =>
                      (this.signupData.vercode = text.toString())
                    }
                    keyboardType={'numeric'}
                    underlineColorAndroid="rgba(0,0,0,0)"
                    placeholder={this.store.text.verificationCode}
                    placeholderStyle={{
                      fontWeight: 'bold',
                      fontFamily: Fonts.century,
                      fontSize: size.getSize(10),
                    }}
                    placeholderTextColor={colors.textColor}
                  />
                </View>
              </View>

              <View
                style={{
                  justifyContent: 'center',
                  alignItems: 'center',
                  height: 60,
                  width: '100%',
                }}></View>
            </View>
          </KeyboardAwareScrollView>
          <TouchableHighlight
            style={styles.buttonView}
            onPress={() => {
              //  this.store.signupPost(this, this.signupData);
              this.signupAction();
            }}>
            <Text style={styles.buttonText}>
              {this.props.navigation.state.params.addphone
                ? this.store.text.addPhone
                : this.store.text.signup}
            </Text>
          </TouchableHighlight>
        </View>
        <Toast
          ref="toast"
          style={{backgroundColor: colors.mainColor}}
          position="bottom"
          positionValue={200}
          fadeInDuration={750}
          fadeOutDuration={2000}
          opacity={0.8}
          textStyle={{color: 'white'}}
        />
      </View>
    );
  }
}

const styles = StyleSheet.flatten({
  textView: {
    color: colors.textColor,
    fontFamily: Fonts.ubuntuL,
    fontSize: size.getSize(13),
  },
  buttonText: {
    color: '#fff',
  },
  buttonView: {
    backgroundColor: colors.mainColor,
    marginRight: 30,
    marginLeft: 30,
    marginTop: 30,
    marginBottom: 30,
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 10,
  },
  buttonText: {
    fontSize: 15,
    fontFamily: Fonts.ubuntu,
    color: 'white',
  },
  container: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: 'white',
  },

  mainContainer: {
    width: width,
    flex: 1,
  },

  loginButton: {
    width: scale(200),
    height: verticalScale(50),
    marginTop: moderateScale(30),
  },

  signupButton: {
    width: width,
    height: verticalScale(50),
  },
  phoneCell: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 15,
    height: 40,
    borderBottomWidth: 1,
    borderColor: '#ebebeb',
    width: width,
    backgroundColor: '#fff',
  },
  phoneInfo: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  input: {
    height: 30,
    width: width * 0.4,
    marginLeft: 10,
    padding: 0,
    fontSize: 14,
  },
  countdown: {
    borderRadius: 5,
    borderWidth: 2,
    borderColor: colors.textColor,
    height: verticalScale(40),
    justifyContent: 'center',
    alignItems: 'center',
  },
  countdownTitle: {
    color: colors.textColor,
    fontSize: 12,
  },
  signupButton: {
    backgroundColor: colors.textColor,
    width: width,
    height: verticalScale(60),
    justifyContent: 'center',
    alignItems: 'center',
  },
});
