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 cookie from 'react-cookies'
let path;
var jwt_decode = require("jwt-decode");
class Phonesteptwo 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-2")  {
        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,
      count:localStorage.getItem("count"),
      is_active: localStorage.getItem("login_is_active") == 1 ? true : false,
      phone_number_complete: false,
      show_error:false,
      error:""
    };
    this.handleNumberSubmit.bind(this);
    this.formatPhone = this.formatPhone.bind(this);
    // this.complete.bind(this);
    // this.handleVerifyCodeSubmit.bind(this);
    // this.handleCall.bind(this);
  }

  componentDidMount = () => {
    this.setState({
      phone_number: localStorage.getItem("phone_number"),
      phone_number_complete: false,
      verification: false
    });
  };

  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.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.success === true) {
              self.setState({ loader: false });
              self.setState({ show_error: true, error: response.data.message });
              localStorage.setItem("current_state", "phone_number_step-3"),
              self.props.history.push("/phone_number_step-3");
              // self.setState({ verification: true });
            } else {
              self.setState({ loader: false });
              self.setState({ show_error: true, error: "Phone Number Not Valid" });
            }
          } 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"
        });
        });
    }
  };

  formatPhone = obj => {
    if (this.state.count < 10) {
      this.setState({ count: this.state.count + 1 });
    }

    var numbers = obj.replace(/\D/g, "");
    console.log("obj", obj);
    let char = { 0: "(", 3: ")", 6: "-" };
    obj = "";
    for (var i = 0; i < numbers.length; i++) {
      obj += (char[i] || "") + numbers[i];
    }
    this.setState({ phone_number: obj });
    console.log("obj", obj);
  };

  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="add_info_upr">
                <div className="add_info">
                  <p>
                    {" "}
                    Additional information is required to complete your entry{" "}
                  </p>
                </div>
              </div>

              <div className="ver_code_upr">
                <div className="ver_code">
                  <div className="vercode_img">
                    {" "}
                    <img src={api.image_path+"verfication.png"} title="" alt="" />{" "}
                  </div>
                  <div className="vercode_txt">
                    <p>
                      {" "}
                      A text message with <br />
                      <b> a verification code </b> <br />
                      will be sent to your number
                    </p>
                  </div>
                </div>
              </div>

              <div className="num_scetion_upr">
                <div className="num_scetion">
                  <p> Please enter your mobile number </p>
                  <div className="mask_scetion">
                  {!this.state.edit_phone_number &&
                    <label>{this.state.phone_number}</label>
                  }
                  {this.state.edit_phone_number &&
                    <input
                      autoFocus={this.state.edit_phone_number}
                      value={this.state.phone_number}
                      onChange={event => this.formatPhone(event.target.value)}
                      /* onChange={event => {
                        const re = /^[0-9\b]+$/;
                        if (
                          event.target.value == "" ||
                          re.test(event.target.value)
                        ) {
                          this.setState({
                            phone_number_complete: true,
                            phone_number: event.target.value
                          });
                        }
                      }} */
                      onKeyPress={event => {
                        {
                          /* console.log(this.state.phone_number); */
                        }
                        if (event.key === "Enter") {
                          if (this.state.count === 10) {
                            {
                              localStorage.setItem(
                                "phone_number",
                                this.state.phone_number
                              );
                              this.handleNumberSubmit();
                            }
                          } else {
                            console.log("Phone Number is not valid");
                            this.setState({
                              show_error: true,
                              error: "Phone Number 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 className="edit_num">
                    {" "}
                    <a
                      onClick={() => this.setState({ edit_phone_number: true })}
                    >
                      Edit number{" "}
                    </a>{" "}
                  </div>
                  <div className="phonenumber_btnsend">
                   <button onClick={() => {
                        this.handleNumberSubmit()
                      }} className="btnsend">Send</button>
                  </div>
                </div>
              </div>
              <div className="phonenumber_text">
                   <p>By continuing, I authorize family.one to contact me at the Phone Number I
                      have specified even if I have registered my Phone Number on a Do Not Call
                      List. In the event that I participate in a Program (contest, freebie or
                      other program) through family.one where my Phone Number is required,
                      I authorize family.one to include my Phone Number in registration for the 
                      specified Program. I understand that each Program will include their own 
                      Privacy Policy, Terms and Conditions available for my review prior to entry
                      explaining how my Phone Number will be used, and that I may refuse to provide
                      my Phone Number for a Program by not entering.
                   </p>
                  </div>  
              <div className="ph_cancle_phonetwo">
                {" "}
                <a
                  onClick={() =>
                    {localStorage.setItem("current_state", "phone_number"),this.props.history.push("/phone_number")}
                  }
                >
                  Cancel{" "}
                </a>{" "}
              </div>
            </div>
          </div>
        </div>
            )}
      </div>
     </div> 
    );
  }
}
const styles = {};

export default Phonesteptwo;
