import React, { Component } from "react";
import {
  Platform,
  StyleSheet,
  View,
  TextInput,
  TouchableOpacity
} from "react-native";
import { observable } from "mobx";
import { observer, inject } from "mobx-react/native";
import Text from "react-native-text";
import { scale, verticalScale, moderateScale } from "react-native-size-matters";
import { Dropdown } from "react-native-material-dropdown";
import { Button } from "react-native-elements";
import firebase from "react-native-firebase";
import Toast, { DURATION } from "react-native-easy-toast";
//component
import DrawerNavigationHeader from "../../components/Public/drawerNavigationHeader";
import theme from "../../config/colors";
import { Fonts } from "../../config/fonts";
import Size from "../../config/size";
import Countdown, { CountdownStatus } from "rn-countdown";
// function
import { width, height } from "../../config/screen";
import AsyncStorageHelper from "../../config/asyncStorageHelper";
import Loader from "../../components/Public/loader";

const asyncStorageHelper = new AsyncStorageHelper();
const size = new Size();

@inject(["menuStore"], ["userStore"])
@observer
export default class AccountSettings extends Component {
  @observable pickupPointIndexExist = false;
  password = "";
  pickupPoint = [];
  @observable index = 1;
  @observable
  code = 0;
  @observable
  password = "";
  @observable
  verificationCode = "";
  static navigationOptions = {
    drawerLabel: "Account"
  };

  constructor(props) {
    super(props);
    this.store = this.props.userStore;
    this.menuStore = this.props.menuStore;
  }
  navigatieAction(page, Param) {
    this.props.navigation.navigate(page, Param);
  }
  checking() {
    asyncStorageHelper.getData("pickupPointId", pickupPointId => {
      if (pickupPointId != null) {
        console.log("index: " + pickupPointId);
        this.pickupPointIndexExist = true;
        this.index = this.getIndex(pickupPointId);
      }
    });
  }

  changeIndex(index) {
    this.tabMap.index = index;
  }

  positionValue() {
    if (this.pickupPointIndexExist) {
      return this.store.pickupPointLabel[this.pickupPointIndex].value;
    } else {
      return null;
    }
  }

  positionChange(id) {
    asyncStorageHelper.saveData("pickupPointId", id);
    this.menuStore.getMenuItem();
  }

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

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

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

    bodyFormData.append("country_code", "852");
    bodyFormData.append(
      "phone_number",
      this.store.userData.data.member.mobile.toString()
    );

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

  getIndex(id) {
    var index = this.store.pickupPointLabel.findIndex(function(item, i) {
      return item.id == parseInt(id);
    });
    return index;
  }

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

  resetPassword() {
    // this.store.signupPost(api.signup, this.signInData, this);
    if (this.verificationCode != null || this.verificationCode != "") {
      if (this.password != null || this.password != "") {
        if (this.password.length >= 8) {
          var data = {
            verificationCode: this.verificationCode,
            mobile: this.store.userData.data.member.mobile.toString(),
            countryCode: "852",
            password: this.password
          };
          this.store.forgotPassword(data, this);
        } else {
          this.refs.toast.show("your password must be at least 8 characters");
        }
      } else {
        this.refs.toast.show("Please enter reset password");
      }
    } else {
      this.refs.toast.show("Please enter verification number");
    }
  }

  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 = "send";
                containerStyle = styles.countdown;
                titleStyle = styles.countdownTitle;
                break;
            }
            return (
              <View style={containerStyle}>
                <Text style={titleStyle}>{title}</Text>
              </View>
            );
          }}
        </Countdown>
      </View>
    );
  }

  render() {
    if (this.store.logined) {
      this.checking();
      return (
        <View style={styles.container}>
          <Loader loading={this.store.loading} />
          <View style={{ flex: 1 }}>
            <View style={styles.TextContainer}>
              <Text
                style={styles.TextView}
                underlineColorAndroid="rgba(0,0,0,0)"
              >
                {this.store.userData.data.member.name}
              </Text>
            </View>
            <View style={styles.TextContainer}>
              <Text style={styles.TextView}>
                {this.store.userData.data.member.email}
              </Text>
            </View>
            <View style={styles.TextContainer}>
              <Text style={styles.TextView}>
                +{this.store.userData.data.member.countryCode}{" "}
                {this.store.userData.data.member.mobile}
              </Text>
            </View>

            <View style={styles.TextContainer}>
              <TextInput
                style={styles.TextView}
                placeholder={"Reset Password(at least 8 characters)"}
                secureTextEntry={true}
                underlineColorAndroid="rgba(0,0,0,0)"
                value={this.password}
                onChangeText={value => (this.password = value)}
              />
            </View>
            <View
              style={{
                marginLeft: 20,
                marginRight: 20,
                marginTop: 20,
                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,
                    paddingVertical: 0,
                    alignSelf: 'stretch'
                  }}
                  underlineColorAndroid="rgba(0,0,0,0)"
                  placeholder="verification no."
                  keyboardType={"numeric"}
                  placeholderStyle={{
                    fontWeight: "bold",
                    fontFamily: Fonts.century,
                    fontSize: size.getSize(10),
                    paddingVertical: 0
                  }}
                  value={this.verificationCode}
                  onChangeText={text => (this.verificationCode = text)}
                  placeholderTextColor={theme.foodNameColor}
                />
              </View>
            </View>
          </View>
          <Button
            title="Reset"
            fontWeight="bold"
            fontSize={size.getSize(18)}
            fontFamily={Fonts.century}
            titleStyle={{
              color: "white",
              fontFamily: Fonts.century,
              fontWeight: "bold",
              fontSize: 50
            }}
            onPress={() => this.resetPassword()}
            // loading={false}
            loadingProps={{ size: "large", color: "rgba(111, 202, 186, 1)" }}
            buttonStyle={styles.signupButton}
          />
          <Toast ref="toast" position={"center"} />
        </View>
      );
    } else {
      return null;
    }
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    backgroundColor: "white",
    width: width
  },
  welcome: {
    fontSize: 20,
    textAlign: "center",
    margin: 10
  },
  instructions: {
    textAlign: "center",
    color: "#333333",
    marginBottom: 5
  },
  TextView: {
    color: theme.coolGrey,
    fontSize: size.getSize(15),
    paddingRight: 20,
    paddingLeft: 20,
    fontWeight: "bold",
    fontFamily: Fonts.century
  },
  TextContainer: {
    backgroundColor: theme.inputBgc,
    marginTop: 20,
    marginLeft: 20,
    marginRight: 20,
    width: width - 40,
    height: verticalScale(40),
    borderRadius: 5,
    justifyContent: "center"
  },
  signupButton: {
    width: width,
    height: verticalScale(60),
    backgroundColor: theme.mainColor
  },
  countdown: {
    borderRadius: 5,
    borderWidth: 2,
    borderColor: theme.coolGrey,
    height: verticalScale(40),
    justifyContent: "center",
    alignItems: "center"
  },
  countdownTitle: {
    color: theme.coolGrey,
    fontSize: 12
  }
});
