import React, { Component } from "react";
import {
  Platform,
  StyleSheet,
  View,
  TextInput,
  TouchableOpacity,
  SafeAreaView,
  Keyboard,
  TouchableWithoutFeedback
} from "react-native";
import { observable } from "mobx";
import { observer, inject } from "mobx-react/native";
import Text from "react-native-text";
import Log from '../../config/log'
import theme from "../../config/colors";
import Header from "../../components/Public/signInUpHeader";
import { scale, verticalScale, moderateScale } from "react-native-size-matters";
import Size from "../../config/size";
import { width, height } from "../../config/screen";
import { Button } from "react-native-elements";
import CheckBox from "react-native-check-box";
import CommonTextInput from "../../components/Public/commonTextInput";
import api from "../../stores/api";
import CodeInput from "react-native-confirmation-code-input";
const size = new Size();
import Toast, { DURATION } from "react-native-easy-toast";
import Countdown, { CountdownStatus } from "rn-countdown";
import { Fonts } from "../../config/fonts";
let log = new Log();
@inject(["userStore"])
@observer
export default class ForgetPassword extends Component {
  @observable
  resend = false;
  @observable
  mobile = "";
  @observable
  password = "";
  @observable
  confirmPassword = "";
  @observable
  verificationCode = "";

  constructor(props) {
    super(props);
    this.store = this.props.userStore;
  }

  componentDidMount() {
    //   this.startToCount();
    log.firebaseClass('forget_password')
  }

  componentWillUnmount = () => {
    //   clearInterval(this.interval);
  };

  state = { checked: false };

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

  startToCount() {
    this.interval = setInterval(() => {
      this.count();
    }, 1000);
  }

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

  resetPassword() {
  
    // this.store.signupPost(api.signup, this.signInData, this);
    if (this.verificationCode != null || this.verificationCode != "") {
      if (this.password != null || this.password != "") {
        if (this.confirmPassword != null || this.confirmPassword != "") {
          if (this.confirmPassword == this.password) {
            var data = {
              verificationCode: this.verificationCode,
              mobile: this.mobile,
              countryCode: "852",
              password: this.password
            };
            log.firebaseLog('press_forgetpassword_button',{mobile:this.mobile})
            this.store.forgotPassword(data,this)
          } else {
            this.refs.toast.show("Password and confirm password is not match");
          }
        } else {
          this.refs.toast.show("Please enter confirm new password");
        }
      } else {
        this.refs.toast.show("Please enter new password");
      }
    } else {
      this.refs.toast.show("Please enter new verification number");
    }
  }

  resendAction() {
    this.store.countdown = 10;
    this.resend = false;
    this.startToCount();
  }

  handleClickCountdown = () => {
    if (this.mobile != "" || this.mobile != null) {
      var bodyFormData = new FormData();

      bodyFormData.append("country_code", "852");
      bodyFormData.append("phone_number", this.mobile.toString());

      this.store.sendsmsVerify(bodyFormData, this);
    } else {
      this.refs.toast.show("Please enter your mobile number");
    }
  };

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

  backAction() {
    this.props.navigation.goBack();
  }

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

  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 (
      <SafeAreaView style={{ flex: 1, backgroundColor: theme.mainColor }}>
        <TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
          <View style={styles.container}>
            <View style={styles.mainContainer}>
              <Header navigation={this.props.navigation} back = {true} />
              <CommonTextInput
                value={this.mobile}
                onChangeText={mobile => (this.mobile = mobile)}
                placeholder="Mobile number"
                secureTextEntry={false}
                returnKeyType={"next"}
                onSubmitEditing={event => {
                  this.verifyInput.focus();
                }}
              />
              <View
                style={{
                  marginLeft: 20,
                  marginRight: 20,
                  marginTop: 30,
                  flexDirection: "row",
                  justifyContent: "space-between"
                }}
              >
                {this.countDownButton()}

                <View
                  style={{
                    backgroundColor: theme.inputBgc,
                    marginLeft: 10,
                    alignSelf: 'stretch',
                    justifyContent: "center",
                    height: verticalScale(40),
                    borderRadius: 5,
                    flex: 1
                  }}
                >
                  <TextInput
                    style={{
                      // backgroundColor:theme.inputBgc,
                      color: theme.foodNameColor,
                      fontSize: size.getSize(12),
                      paddingRight: 30,
                      paddingLeft: 40,
                      fontFamily: Fonts.century,
                      alignSelf: 'stretch'
                    }}
                    underlineColorAndroid="rgba(0,0,0,0)"
                    placeholder="verificcation no."
                    keyboardType={"numeric"}
                    placeholderStyle={{
                      fontWeight: "bold",
                      fontFamily: Fonts.century,
                      fontSize: size.getSize(10)
                    }}
                    ref={input => {
                      this.verifyInput = input;
                    }}
                    onChangeText={text => (this.verificationCode = text)}
                    placeholderTextColor={theme.foodNameColor}
                    returnKeyType={"next"}
                    onSubmitEditing={event => {
                      this.passwordInput.focus();
                    }}
                  />
                </View>
              </View>

              <CommonTextInput
                value={this.password}
                onChangeText={mobile => (this.password = mobile)}
                placeholder="new password"
                secureTextEntry={true}
                returnKeyType={"next"}
                inputRef={input => {
                  this.passwordInput = input;
                }}
                onSubmitEditing={event => {
                  this.confirmPasswordInput.focus();
                }}
              />

              <CommonTextInput
                value={this.confirmPassword}
                onChangeText={confirmPassword =>
                  (this.confirmPassword = confirmPassword)
                }
                placeholder="confirm new Password"
                secureTextEntry={true}
                returnKeyType={"done"}
                inputRef={input => {
                  this.confirmPasswordInput = input;
                }}
                onSubmitEditing={event => {
                  Keyboard.dismiss()
                }}
              />
            </View>

            <Toast ref="toast" />
            <TouchableOpacity
              style={styles.signupButton}
              onPress={() => {
                this.resetPassword();
              }}
            >
              <Text
                style={{
                  fontSize: 18,
                  fontFamily: Fonts.century,
                  color: "white",
                  fontWeight: "bold"
                }}
              >
                Reset
              </Text>
            </TouchableOpacity>
          </View>
        </TouchableWithoutFeedback>
      </SafeAreaView>
    );
  }
}

const styles = StyleSheet.create({
  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: theme.coolGrey,
    height: verticalScale(40),
    justifyContent: "center",
    alignItems: "center"
  },
  countdownTitle: {
    color: theme.coolGrey,
    fontSize: 12
  },
  signupButton: {
    backgroundColor: theme.mainColor,
    width: width,
    height: verticalScale(60),
    justifyContent: "center",
    alignItems: "center"
  }
});
