import React, { Component } from "react";
import FlatButton from "material-ui/FlatButton";
import Dialog from "material-ui/Dialog";
import { slideInRight } from "react-animations";
import Radium, { StyleRoot } from "radium";
import axios from "axios";
import CircularProgress from "@material-ui/core/CircularProgress";
import isMobile from "react-device-detect";
import api from "./api/api";
import InputMask from "react-input-mask";
import { truncate } from "fs";
import cookie from 'react-cookies'
let path;
var jwt_decode = require("jwt-decode");
class Phonestepthree extends Component {
  constructor(props) {
    super(props);
    console.log("session", localStorage.getItem("current_state"));
    console.log("is_active", localStorage.getItem("login_is_active"));
    if (
      localStorage.getItem("current_state") !== "phone_number_step-3" )  {
        this.props.history.push("/menu_page");
      }
    this.state = {
      edit_phone_number: false,
      open: false,
      alertmsg: "",
      phone_number: localStorage.getItem("phone_number"),
      verification: false,
      verify_code: "",
      is_verified: "",
      loader: false,
      is_active: localStorage.getItem("login_is_active") == 1 ? true : false,
      phone_number_complete: false,
      verify_code_complete:false,
      show_error: false,
      error: ""
    };
    this.handleNumberSubmit.bind(this);
    // this.complete.bind(this);
    this.handleVerifyCodeSubmit.bind(this);
    this.handleCall.bind(this);
  }
  handleNumberSubmit = () => {
    //console.log("handle submit is clicked", this.state);
    let finalJson = this.state.finalJson;
    // let action = this.props.resetState;
    // let redirect = this.props.history;

    if (this.state.phone_number === "" || !this.state.phone_number) {
      this.setState({ show_error: true, error: "Phone Number is not valid" });
      self.setState({ loader: false });
      if (!this.state.verification) {
        this.setState({ verification: true });
      }
    } else {
      let phone_number = this.state.phone_number;

      if (phone_number !== null) {
        phone_number = phone_number.replace('"', "");
        phone_number.replace(/[`~!@#$%^&*()_|+\-=÷¿?;:'",.<>\\]/gi, "\\$&");
      }
      finalJson = {
        action: "send_code",
        phone_number: phone_number,
        country_code: "+1",
        via: "sms"
      };
      console.log("finalJson", finalJson);
      var self = this;
      self.setState({ loader: true });
      axios
        .request({
          method: "POST",
          url: api.mobile_verify,
          data: JSON.stringify(finalJson)
        })
        .then(function(response) {
          console.log("response", response);
          if (response.status === 200) {
            if (response.data.is_cellphone) {
              self.setState({ loader: false });
              self.setState({ verification: true });
            } else {
              self.setState({ loader: false });
              self.setState({ show_error: true, error: response.data.message });
              //   if(finalJson.country_code == "+91"){
              //     self.setState({ verification: true });
              //   }
            }
          } else {
            self.setState({ loader: false });
            self.setState({ show_error: true, error: "Something Wrong" });
          }
        })
        .catch(function(error) {
          self.setState({ loader: false });
          self.setState({ loader: false });
        self.setState({
          show_error: true,
          error: "Something Wrong... Please try Again"
        });
        });
    }
  };
  handleCall = () => {
    console.log("handle submit is clicked", this.state);
    let finalJson = this.state.finalJson;
    // let action = this.props.resetState;
    // let redirect = this.props.history;

    if (this.state.phone_number === "" || !this.state.phone_number) {
      this.setState({ show_error: true, error: "Phone Number is not valid" });
      self.setState({ loader: false });
      if (!this.state.verification) {
        this.setState({ verification: true });
      }
    } else {
      let phone_number = this.state.phone_number;

      if (phone_number !== null) {
        phone_number = phone_number.replace('"', "");
        phone_number.replace(/[`~!@#$%^&*()_|+\-=÷¿?;:'",.<>\\]/gi, "\\$&");
      }
      finalJson = {
        action: "send_code",
        phone_number: phone_number,
        country_code: "+1",
        via: "call"
      };
      console.log("finalJosn", finalJson);
      var self = this;
      self.setState({ loader: true });
      axios
        .request({
          method: "POST",
          url: api.mobile_verify,
          data: JSON.stringify(finalJson)
        })
        .then(function(response) {
          console.log("resposne", response);
          if (response.status === 200) {
            if (response.data.is_cellphone) {
              self.setState({ loader: false });
              self.setState({ verification: true });
            } else {
              self.setState({ loader: false });
              self.setState({ show_error: true, error: response.data.message });
            }
          } else {
            self.setState({ loader: false });
            self.setState({ show_error: true, error: "Something Wrong..." });
          }
        })
        .catch(function(error) {
          self.setState({ loader: false });
        self.setState({
          show_error: true,
          error: "Something Wrong... Please try Again"
        });
        });
    }
  };

  handleVerifyCodeSubmit = () => {
    let finalJson = this.state.finalJson;
    // let action = this.props.resetState;
    let redirect = this.props.history;

    if (this.state.verify_code === "" || !this.state.verify_code) {
      this.setState({
        show_error: true,
        error: "Verify Code should not be empty"
      });
      localStorage.setItem("current_state", "skill_test_questions");
      // redirect.push("/skill_test_questions");
    } else if (!this.state.verify_code.match(/^\d{6}$/)) {
      this.setState({ show_error: true, error: "Verify Codes is not valid" });
    } else {
      let verify_code = this.state.verify_code;
      let phone_number = this.state.phone_number;
      if (verify_code !== null) {
        verify_code = verify_code.replace('"', "");
        verify_code.replace(/[`~!@#$%^&*()_|+\-=÷¿?;:'",.<>\\]/gi, "\\$&");
      }
      if (phone_number !== null) {
        phone_number = phone_number.replace('"', "");
        phone_number.replace(/[`~!@#$%^&*()_|+\-=÷¿?;:'",.<>\\]/gi, "\\$&");
      }

      this.setState({ verify_code: "" });

      finalJson = {
        action: "verify_code",
        verification_code: verify_code,
        phone_number: phone_number,
        country_code: "+1"
      };
      console.log("finalJson", finalJson);
      var self = this;
      self.setState({ loader: true });

      axios
        .request({
          method: "POST",
          url: api.mobile_verify,
          data: JSON.stringify(finalJson)
        })
        .then(function(response) {
          console.log("response", response);
          if (response.data.success === true) {
            var updateJson = {
              action: "update",
              user_id: cookie.load("user_id"),
              user_metadata: {
                phone_verified: true,
                phone_number: localStorage.getItem("phone_number"),
                phone_number_enter_date: new Date()
              }
            };
            console.log("updateJson", updateJson);
            axios
              .request({
                method: "POST",
                url: api.react_request,
                data: JSON.stringify(updateJson)
              })
              .then(response => {
                console.log("response", response);
                console.log(
                  "contest",
                  JSON.parse(localStorage.getItem("contest_array"))
                );
                let contest_array = JSON.parse(
                  localStorage.getItem("contest_array")
                );
                let contest_index = localStorage.getItem("contest_index");
                console.log("id", contest_array[contest_index]);
                if (response.status == 200) {
                  if (contest_array[contest_index].is_skill_required == "1") {
                    console.log("here");
                    if (
                      localStorage.getItem("skill_test_question") == true ||
                      localStorage.getItem("skill_test_question") == "true"
                    ) {
                      console.log("here");
                      if (
                        contest_array[contest_index].is_user_age_required == "1"
                      ) {
                        console.log("here");
                        if (
                          localStorage.getItem("user_age_required") == true ||
                          localStorage.getItem("user_age_required") == "true"
                        ) {
                          self.setState({ loader: false });
                          localStorage.setItem("current_state", "share"),
                            self.props.history.push({ pathname: "/share" });
                          console.log("here");
                        } else {
                          console.log("here");
                          self.setState({ loader: false });
                          localStorage.setItem(
                            "current_state",
                            "user_birthdate"
                          );
                          self.props.history.push({
                            pathname: "/user_birthdate"
                          });
                        }
                      } else {
                        console.log("here");
                        self.setState({ loader: false });
                        localStorage.setItem("current_state", "share"),
                          self.props.history.push({ pathname: "/share" });
                      }
                    } else {
                      console.log("here");
                      self.setState({ loader: false });
                      localStorage.setItem(
                        "current_state",
                        "skill_test_questions"
                      );
                      self.props.history.push({
                        pathname: "/skill_test_questions"
                      });
                    }
                  } else if (
                    self.state.contest[self.state.id].is_user_age_required ==
                    "1"
                  ) {
                    console.log("here");
                    if (
                      localStorage.getItem("user_age_required") == true ||
                      localStorage.getItem("user_age_required") == "true"
                    ) {
                      self.setState({ loader: false });
                      localStorage.setItem("current_state", "share"),
                        self.props.history.push({ pathname: "/share" });
                      console.log("here");
                    } else {
                      console.log("here");
                      self.setState({ loader: false });
                      localStorage.setItem("current_state", "user_birthdate");
                      self.props.history.push({
                        pathname: "/user_birthdate"
                      });
                    }
                  } else {
                    localStorage.setItem("current_state", "share"),
                      self.props.history.push({ pathname: "/share" });
                  }
                } else {
                  self.setState({ loader: false });
                  self.setState({
                    show_error: true,
                    error: "Something Wrong... Please Try Again Later"
                  });
                }
              })
              .catch(error => {
                console.log("error", error);
                self.setState({ loader: false });
                self.setState({
                  show_error: true,
                  error: "Something Wrong... Please Try Again Later"
                });
              });
          } else {
            self.setState({ loader: false });
            self.setState({
              show_error: true,
              error: "Incorrect code, please try again"
            });
          }
        })
        .catch(function(error) {
          console.log("error", error);
          self.setState({ loader: false });
          self.setState({
            show_error: true,
            error: "Something Wrong... Please Try Again Later"
          });
        });
    }
  };

  handleClose = () => {
    this.setState({ open: false });
  };

  render() {
    return (
      <div className="bcd_header_div_margin">
        <div className="allpages_desktop_boxes_div setrelation_header_div phoneno_three_header_div">
          {this.state.loader && (
            <CircularProgress
              size={100}
              style={{ color: "black", marginTop: "17%" }}
            />
          )}
          <Dialog
            style={{ textTransform: "capitalize" }}
            actions={
              <FlatButton
                label="Close"
                labelStyle={{ color: "#000" }}
                onClick={this.handleClose.bind(this)}
              />
            }
            modal={false}
            open={this.state.open}
          >
            {this.state.alertmsg}
          </Dialog>
          {!this.state.loader && (
            <div className="phone_class">
              <div className="">
                <div>
                  <div className="num_scetion_upr">
                    <div className="num_scetion mask_scetion_final">
                      <p> Please enter your mobile number </p>
                      <div className="mask_scetion">
                        <label>{this.state.phone_number}</label>
                      </div>

                      {/* <div className="num_scetion_pre">
                    {" "}
                    <img onClick={()=> this.props.history.push("/phone_number_step-2")}  src="images/prev_arrow_one.jpg" />{" "}
                  </div> */}
                    </div>
                  </div>

                  <div className="num_scetion_upr num_scetion_final">
                    <div className="num_scetion">
                      <p>Enter the Verification Code </p>
                      <div className="mask_scetion">
                        <input
                          autoFocus={true}
                          value={this.state.verify_code}
                          onChange={event => {
                            const re = /^[0-9\b]+$/;
                            if (
                              event.target.value !== "" ||
                              re.test(event.target.value)
                            ) {
                              this.setState({
                                verify_code: event.target.value
                              });
                            }
                            if(event.target.value.length === 6){
                              this.setState({
                                verify_code_complete: true
                              });
                            }
                            else{
                              this.setState({
                                verify_code_complete: false
                              });
                            }
                          }}
                          onKeyPress={event => {
                            {
                              /* console.log(this.state.phone_number); */
                            }
                            if (event.key === "Enter") {
                              if (event.target.value.length === 6) {
                                {
                                  this.handleVerifyCodeSubmit();
                                }
                              } else {
                                console.log("Verification Code is not valid");
                                this.setState({
                                  show_error: true,
                                  error: "Verification Code is not valid"
                                });
                              }
                            }
                          }}
                        />
                      </div>
                      {this.state.show_error && (
                        <div className="bcd_shownotification_div">
                          <img
                            src={api.image_path+"error-msg-icon.png"}
                            alt="notify img"
                          />
                          <p className="notify_para">{this.state.error}</p>
                          <div className="bcd_shownotification_div1">
                            <a
                              onClick={() => {
                                this.setState({ show_error: false });
                              }}
                              className="notify_para1"
                            >
                              X
                            </a>
                          </div>
                        </div>
                      )}
                    </div>
                    <div className="">
                          {this.state.verify_code_complete && (
                            <div className="next_btn_div">
                              <button
                                onClick={() => this.handleVerifyCodeSubmit()}
                                className="varificationcode_btnsubmit"
                              >
                                Submit
                              </button>
                            </div>
                          )}
                            </div>
                  </div>

                  <div className="resend_call">
                     {/* <div className="row sharebtn_div user_birthdate_pare_div">
                        <button
                          // onClick={() => {
                          //   this.link_contest();
                          // }}
                          className="btn_SocialShare user_birthdate_btn"
                        >
                        Enter
                        </button>
                      </div><br/> */}
                    <a onClick={() => this.handleNumberSubmit()}>
                      Resend{" "}
                    </a>{" "}
                    <a>|</a> <a onClick={() => this.handleCall()}>Call </a>{" "}
                  </div>
                </div>
              </div>
            </div>
          )}
          <div className="fac_btn_arrrow">
            <div className="fac_btn_prev_div">
              <img
                src={api.image_path+"prev_arrow_one.jpg"}
                width="40"
                className="next_icon next_left"
                onClick={() => {localStorage.setItem("current_state", "phone_number_step-2"),this.props.history.push("/phone_number_step-2")}}
                // onClick={() => {
                //   this.props.history.push("/");
                // }}
              />
            </div>
            <div className="fac_btn_next_div">
              <img
                src={api.image_path+"next_arrow_one.png"}
                width="40"
                className="next_icon next_right"
                onClick={() => this.handleVerifyCodeSubmit()}
                // onClick={() => {
                //   this.handleSubmit();
                // }}
              />
            </div>
          </div>
        </div>
      </div>
    );
  }
}
const styles = {};

export default Phonestepthree;
