import React from 'react';
import {
  SafeAreaView,
  Text,
  View,
  TouchableOpacity,
  TouchableHighlight,
  Image,
  TextInput,
  Keyboard,
  StyleSheet,
  ImageBackground
} from 'react-native';
import { inject, observer } from "mobx-react"
import { observable, makeObservable } from 'mobx'
import { images } from '../../assets/images/imageIndex';
import Toast, { DURATION } from 'react-native-easy-toast';
import {
  CodeField,
  Cursor,
  useBlurOnFulfill,
  useClearByFocusCell,
} from 'react-native-confirmation-code-field';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import { width, height } from '../../services/screen';
import { colors } from '../../assets/styles/colors-theme';
var _ = require('lodash');
import Icon from 'react-native-vector-icons/dist/MaterialIcons';
import Icon2 from 'react-native-vector-icons/dist/Ionicons';
import CustomTextInput from '../../components/customTextInput';
import CustomLoginButton from '../../components/customLoginButton';
import I18n from '../../services/i18n'
import TitleBar from '../../components/titleBar'
Icon.loadFont();
const CELL_COUNT = 6;
const SignUpVerify = inject("appStore")(observer(class SignUpVerify extends React.Component {


  phoneVerification = '';

  signupData = this.props.route.params.data;

  addMobile = this.props.route.params.addMobile;

  sendstate = true;

  countryCode = '852';

  thirdParty = false;

  backupMobile = '';

  code = ''
  constructor(props) {
    super(props);
    this.store = props.appStore;
    this.state = {
      countryCode: '852',
    };
    makeObservable(this, {
      phoneVerification: observable,

      signupData: observable,

      addMobile: observable,

      sendstate: observable,

      countryCode: observable,

      thirdParty: observable,

      backupMobile: observable,

      code: observable,
    })
  }
  componentWillMount() { }


  componentDidMount() {
    var smsData = {
      mobile: this.signupData.mobile.toString(),
      country_code: '+852',
    };
    this.store.startTimer(smsData, this)
  }


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

  startToCount() {
    this.interval = setInterval(() => {
      this.count();
    }, 1000);
  }
  resendAction() {
    this.store.timer = 60;
    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 smsData = {
      mobile: this.signupData.mobile.toString(),
      country_code: '+852',
    };
    this.store.sendsmsVerify(smsData, this);
    this.backupMobile = _.cloneDeep(this.signupData.mobile.toString());
  }

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

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

  sendTextReturn() {
    if (this.sendstate) {
      return 'Send';
    } else {
      return this.store.timer.toString();
    }
  }

  sendAction() {
    if (this.sendstate) {
      if (this.signupData.mobile.length > 6) {
        this.handleClickCountdown();
        clearInterval(this.interval);
        this.store.timer = 60;
        this.sendstate = false;
        this.startToCount();
      } else {
        this.refs.toast.show(I18n.t('pleaseEnterPhone'));
      }
    }
  }

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

  verifyInputAction(code) {
    this.code = code
    if (this.code.length === CELL_COUNT) {
      this.signupData.ver_code = code
      this.store.signupPost(this, this.signupData);
    }
  }

  signupAction() {
    console.log(this.signupData.mobile);
    console.log(this.backupMobile);
    if (!this.addMobile) {
      if (this.signupData.ver_code.length > 0) {
        if (this.backupMobile == this.signupData.mobile) {
          if (this.signupData.name != '') {
            //action
            this.store.signupPost(this, this.signupData);
          } else {
            this.refs.toast.show(I18n.t('pleaseInputYourName'));
          }
        } else {
          this.refs.toast.show('與SMS的電話號碼不符');
        }
      } else {
        this.refs.toast.show('請輸入SMS驗證碼');
      }
    } else {
      if (this.backupMobile == this.signupData.mobile) {
        const data = {
          country_code: this.signupData.country_code,
          mobile: this.signupData.mobile,
          ver_code: this.signupData.ver_code,
        };
        this.store.bindMobile(data, this);
      } else {
        this.refs.toast.show('與SMS的電話號碼不符');
      }
    }
  }

  renderLogoAndPhone() {
    return (
      <View style={{ width: width, justifyContent: 'center', alignItems: 'center', marginTop: 50 }}>
        <Image source={images.titleLogo} />
        <Text style={{ color: colors.fontColor, marginTop: 20, fontWeight: '800' }}>
          {I18n.t('verifyPhoneNumberPleaseEnterPhoneNumber')}
        </Text>
        <Text style={{ color: colors.fontColor, fontWeight: '800' }}>
          {I18n.t('verifyPhoneNumberLast4DigitsAre', { 'phone': this.signupData.mobile.substring(4, 8) })}
        </Text>
      </View>
    )
  }

  renderVerfiyCodeMaskInput() {
    return (
      <View style={{ marginTop: 40 }}>
        <CodeField
          value={this.code}
          onChangeText={text => this.verifyInputAction(text)}
          cellCount={CELL_COUNT}
          rootStyle={styles.codeFieldRoot}
          keyboardType="number-pad"
          textContentType="oneTimeCode"
          renderCell={({ index, symbol, isFocused }) => (
            <View
              // Make sure that you pass onLayout={getCellOnLayoutHandler(index)} prop to root component of "Cell"
              key={index}
              style={[styles.cellRoot, isFocused && styles.focusCell]}>
              <Text style={styles.cellText}>
                {symbol || (isFocused ? <Cursor /> : null)}
              </Text>
            </View>
          )}
        />
      </View>
    )
  }

  renderMessageAndReSendButton() {
    return (
      <View style={{ width: width, justifyContent: 'center', alignItems: 'center', marginTop:40}}>
        <Text style={{ fontSize: 11, color: '#CA9D66' }}>
          {I18n.t('verifyPhoneNumberNoCode')}
        </Text>
        <Text style={{ fontSize: 11, color: colors.fontColor }}>
          {I18n.t('verifyPhoneNumberYouCan')}
          <Text style={{ fontSize: 11, color: colors.fontColor  }}>
            {this.store.countdownHandler(this.store.timer)}
            <Text style={{ fontSize: 11, color:colors.fontColor  }}>
              {I18n.t('verifyPhoneNumberSecPressSendAgain')}
            </Text>
          </Text>
        </Text>
      </View>
    )
  }

  render() {
    return (
      <ImageBackground resizeMode='cover' style={{ flex: 1, backgroundColor: colors.bgc }} source={require('../../assets/images/background.png')} >
        <TitleBar navigation={this.props.navigation} back={true} />
        {this.renderLogoAndPhone()}
        {this.renderVerfiyCodeMaskInput()}
        {this.renderMessageAndReSendButton()}

        <Toast
          ref="toast"
          style={{ backgroundColor: colors.mainColor }}
          position="bottom"
          positionValue={200}
          fadeInDuration={750}
          fadeOutDuration={2000}
          opacity={0.8}
          textStyle={{ color: 'white' }}
        />
      </ImageBackground>
    );
  }
}))

const styles = StyleSheet.flatten({
  textView: {
    fontSize: 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,

    color: 'white',
  },
  container: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: 'white',
  },

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

  loginButton: {
    width: 200,
    height: 50,
    marginTop: 30,
  },

  signupButton: {
    width: width,
    height: 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: 40,
    justifyContent: 'center',
    alignItems: 'center',
  },
  countdownTitle: {
    color: colors.textColor,
    fontSize: 12,
  },
  signupButton: {
    backgroundColor: colors.textColor,
    width: width,
    height: 60,
    justifyContent: 'center',
    alignItems: 'center',
  },
  titleText: {
    fontSize: 20,
    fontWeight: '500',
    textAlign: 'center',
  },
  root: { padding: 20, minHeight: 300 },
  title: { textAlign: 'center', fontSize: 30 },
  codeFieldRoot: {
    marginTop: 20,
    width: 280,
    marginLeft: 'auto',
    marginRight: 'auto',
  },
  cellRoot: {
    width: 30,
    height: 30,
    justifyContent: 'center',
    alignItems: 'center',
    borderBottomColor: '#ccc',
    borderBottomWidth: 2,
  },
  cellText: {
    color: '#000',
    fontSize: 20,
    fontWeight: '800',
    textAlign: 'center',
  },
  focusCell: {
    borderBottomColor: colors.fontColor,
    borderBottomWidth: 2,
  },

});
export default SignUpVerify