import React, { Component } from "react";
import axios from "axios";
import Dialog from "material-ui/Dialog";
import FlatButton from "material-ui/FlatButton";
import { slideInUp, slideInRight } from "react-animations";
import Radium from "radium";
import CircularProgress from "@material-ui/core/CircularProgress";
import FaChevronCircleRight from "react-icons/lib/fa/chevron-circle-right";
import { isMobile, isMobileOnly } from "react-device-detect";
import $ from "jquery";
import api from "./api/api";
import cookie from "react-cookies";
// import test from "./data/data";
class basicContactDetails extends Component {
  constructor(props) {
    console.log("reactrequest", api);
    console.log("session", localStorage.getItem("current_state"));
    console.log("login_is_active", localStorage.getItem("login_is_active"));
    // if (
    //   localStorage.getItem("current_state") !== "signup"
    // ) {
    //   props.history.push("/");
    // }
    super(props);
    this.state = {
      read_email: cookie.load("relative_user_id") ? true : false,
      email:
        localStorage.getItem("login_is_active") === 0
          ? localStorage.getItem("user_email")
          : "",
      firstName:
        localStorage.getItem("login_is_active") === 0
          ? localStorage.getItem("first_name")
          : "",
      lastName:
        localStorage.getItem("login_is_active") === 0
          ? localStorage.getItem("last_name")
          : "",
      open: false,
      alertmsg: "",
      firstname_complete:
        localStorage.getItem("login_is_active") === 0 &&
        localStorage.getItem("first_name")
          ? true
          : false,
      lastname_complete:
        localStorage.getItem("login_is_active") === 0 &&
        localStorage.getItem("last_name")
          ? true
          : false,
      loader: false,
      is_active: localStorage.getItem("login_is_active"),
      error: "",
      show_error: false,
      alternative_email: ""
    };
    this.handleSubmit.bind(this);
  }
  componentDidMount() {
    // if(localStorage.getItem("user_id") !== null){
    console.log("search_email", cookie.load("user_id"));
    if (cookie.load("relative_user_id")) {
      if (cookie.load("relative_user_id").length > 10) {
        let getfinaljson = {
          action: "get_information",
          user_id: cookie.load("relative_user_id")
        };
        console.log("getfinaljson", getfinaljson);
        var self = this;
        self.setState({ loader: true });
        axios
          .request({
            method: "POST",
            url: api.react_request,
            data: JSON.stringify(getfinaljson)
          })
          .then(function(response) {
            console.log("response", response);
            if (response.status === 200) {
              self.setState({
                firstName: response.data.user_metadata.first_name,
                firstname_complete: true,
                lastname_complete: true,
                lastName: response.data.user_metadata.last_name,
                email: response.data.email,
                alternative_email: response.data.email
              });
              self.setState({ loader: false });
            }
          })
          .catch(error => {
            console.log("error", error);
            self.setState({ loader: false });
            self.setState({
              show_error: true,
              error: "Something Wrong... Please try again later"
            });
          });
      }
    }

    if (cookie.load("check_user_id")) {
      if (cookie.load("check_user_id").length > 10) {
        let getfinaljson = {
          action: "get_information",
          user_id: cookie.load("check_user_id")
        };
        console.log("getfinaljson", getfinaljson);
        var self = this;
        self.setState({ loader: true });
        axios
          .request({
            method: "POST",
            url: api.react_request,
            data: JSON.stringify(getfinaljson)
          })
          .then(function(response) {
            console.log("response", response);
            if (response.status === 200) {
              self.setState({
                firstName: response.data.user_metadata.first_name,
                firstname_complete: true,
                lastname_complete: true,
                lastName: response.data.user_metadata.last_name,
                email: response.data.email,
                alternative_email: response.data.email
              });
              self.setState({ loader: false });
            }
          })
          .catch(error => {
            console.log("error", error);
            self.setState({ loader: false });
            self.setState({
              show_error: true,
              error: "Something Wrong... Please try again later"
            });
          });
      }
    }
  }

  handleSubmit = () => {
    console.log("here");
    if (this.state.firstName === "") {
      console.log("here");
      this.setState({
        show_error: true,
        error: "Enter First Name"
      });
    } else if (!this.state.firstname_complete) {
      console.log("here");
      this.setState({ firstname_complete: true });
    } else if (this.state.lastName === "") {
      console.log("here");
      this.setState({
        show_error: true,
        error: "Enter Last Name"
      });
    } else if (!this.state.lastname_complete) {
      console.log("here");
      this.setState({ lastname_complete: true });
    } else if (this.state.email === "" || !this.state.email) {
      console.log("here");
      this.setState({
        show_error: true,
        error: "Enter Email"
      });
    } else if (
      !this.state.email.match(/^([a-zA-Z0-9_.-]+@([\w-]+\.)+[\w-]{2,10})?$/)
    ) {
      this.setState({
        show_error: true,
        error: "Email is not valid"
      });
    } else {
      let email = this.state.email;
      let firstName = this.state.firstName;
      let lastName = this.state.lastName;

      if (email != null) {
        email = email.replace('"', "");
        email.replace(/[`~!@#$%^&*()_|+\-=÷¿?;:'",.<>\\]/gi, "\\$&");
      }
      if (firstName != null) {
        firstName = firstName.replace('"', "");
        firstName.replace(/[`~!@#$%^&*()_|+\-=÷¿?;:'",.<>\\]/gi, "\\$&");
      }
      if (lastName != null) {
        lastName = lastName.replace('"', "");
        lastName.replace(/[`~!@#$%^&*()_|+\-=÷¿?;:'",.<>\\]/gi, "\\$&");
      }
      // this.setState({ loader: true });
      this.setState({ email: "", firstName: "", lastName: "" });
      localStorage.setItem("first_name", firstName);
      localStorage.setItem("last_name", lastName);

      // Search the email id for existence
      let getfinaljson = {
        action: "signup",
        connection: "email",
        name:
          firstName.charAt(0).toUpperCase() +
          firstName.substr(1) +
          " " +
          lastName.charAt(0).toUpperCase() +
          lastName.substr(1),
        nickname:
          firstName.charAt(0).toUpperCase() +
          firstName.substr(1) +
          " " +
          lastName.charAt(0).toUpperCase() +
          lastName.substr(1),
        email:
          this.state.alternative_email == ""
            ? email
            : this.state.alternative_email,

        user_metadata: {
          email_changed:
            this.state.alternative_email !== ""
              ? email === this.state.alternative_email
                ? 0
                : 1
              : 0,
          first_name: firstName.charAt(0).toUpperCase() + firstName.substr(1),
          last_name: lastName.charAt(0).toUpperCase() + lastName.substr(1),
          link_activated: 0,
          offer_orientation: 0,
          contest_orientation: 0,
          related_entrant_orientation: 0,
          someone_else_orientation: 0,
          perks: 0,
          is_active: 1,
          family_one_contest_mail: true,
          alternative_email:
            this.state.alternative_email !== ""
              ? email
              : this.state.alternative_email
        }
      };
      console.log("getfinaljson", getfinaljson);
      var self = this;
      self.setState({ loader: true });
      axios
        .request({
          method: "POST",
          url: api.react_request,
          data: JSON.stringify(getfinaljson)
        })
        .then(function(response) {
          console.log("response", response);
          cookie.remove("check_user_id", { path: "/" });

          if (response.data.existing === 1) {
            self.setState({
              loader: false,
              firstname_complete: false,
              lastname_complete: false
            });
            cookie.remove("refered_by_id", { path: "/" });
            self.setState({ loader: false });
            localStorage.setItem("user_email", email);
            localStorage.setItem("current_state", "exist_user");
            self.props.history.push("/exist_user");
          } else {
            localStorage.setItem("user_email", email);
            localStorage.setItem("name", response.data.name);
            localStorage.setItem(
              "first_name",
              response.data.user_metadata.first_name
            );
            localStorage.setItem(
              "last_name",
              response.data.user_metadata.last_name
            );
            localStorage.setItem(
              "offer_orientation",
              response.data.user_metadata.offer_orientation
            );
            localStorage.setItem("perks", response.data.user_metadata.perks);
            localStorage.setItem(
              "contest_orientation",
              response.data.user_metadata.contest_orientation
            );
            localStorage.setItem("is_signup", "true");
            localStorage.setItem(
              "alternative_email",
              response.data.user_metadata.alternative_email
            );
            if (response.data.user_metadata.relation) {
              localStorage.setItem(
                "relation_data",
                JSON.stringify(response.data.user_metadata.relation)
              );
            }
            localStorage.setItem(
              "someone_else_orientation",
              response.data.user_metadata.someone_else_orientation
            );
            localStorage.setItem(
              "related_entrant_orientation",
              response.data.user_metadata.related_entrant_orientation
            );
            // cookie.save("user_id",response.data.user_id,{ path: '/' })
            cookie.save("user_id", response.data.user_id, { path: "/" });
            if (response.data.imported === 1) {
              localStorage.setItem("imported", response.data.imported);
            }
            // else{
            if (localStorage.getItem("previous") !== "login") {
              localStorage.setItem("user_email", response.data.email);
              localStorage.setItem("user_id", response.data.user_id);
              localStorage.setItem("login_is_active", 0);
              console.log("user_id", cookie.load("user_id"));
              localStorage.setItem("current_state", "address");
              localStorage.setItem("previous", "signup");
            }
            localStorage.setItem("user_email", response.data.email);
            localStorage.setItem("user_id", response.data.user_id);
            localStorage.setItem("login_is_active", 0);
            console.log("user_id", cookie.load("user_id"));
            localStorage.setItem("current_state", "address");
            self.setState({ loader: false });
            cookie.remove("refered_by_id", { path: "/" });
            localStorage.setItem("current_state", "index");
            self.props.history.push("/index");
            // }
          }
        })
        .catch(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 infoicon_paddingdiv">
          <div className="background-images">
            <div className="background_color">
              <div className="" style={styles.slideInRight}>
                <div className="container-fluid">
                  {this.state.loader && (
                    <center>
                      <CircularProgress
                        size={100}
                        style={{ color: "black", marginTop: "17%" }}
                      />
                    </center>
                  )}
                  <Dialog
                    style={{ textTransform: "capitalize" }}
                    actions={
                      <FlatButton
                        label="Close"
                        labelStyle={{ color: "#000" }}
                        onClick={this.handleClose}
                      />
                    }
                    modal={false}
                    open={this.state.open}
                    onRequestClose={this.handleClose}
                  >
                    {this.state.alertmsg}
                  </Dialog>
                  {!this.state.loader && (
                    <div>
                      <div className="info_icon_div">
                        <img
                          src={api.image_path + "info1.png"}
                          alt="info_img"
                          className="info_img"
                          onClick={() => {
                            localStorage.setItem("current_state", "info"),
                              localStorage.setItem("info", "signup"),
                              this.props.history.push("/info");
                          }}
                        />
                      </div>
                      <div className="paddingtop70">
                        <input
                          className="autoscale_username first_Name"
                          type="text"
                          value={this.state.firstName}
                          placeholder="Enter Your First Name"
                          autoFocus="true"
                          autoComplete="off"
                          maxLength={15}
                          style={{
                            fontSize:
                              this.state.firstName.length > 0
                                ? this.state.firstName.length < 15
                                  ? this.state.firstName.length < 3
                                    ? 330 -
                                      this.state.firstName.length *
                                        (this.state.firstName.length * 30)
                                    : 300 -
                                      this.state.firstName.length *
                                        (this.state.firstName.length === 3
                                          ? 55
                                          : this.state.firstName.length === 4
                                            ? 50
                                            : this.state.firstName.length === 5
                                              ? 42
                                              : this.state.firstName.length ===
                                                6
                                                ? 38
                                                : this.state.firstName
                                                    .length === 7
                                                  ? 34
                                                  : this.state.firstName
                                                      .length === 8
                                                    ? 31
                                                    : this.state.firstName
                                                        .length === 9
                                                      ? 28
                                                      : this.state.firstName
                                                          .length === 10
                                                        ? 25.5
                                                        : this.state.firstName
                                                            .length === 11
                                                          ? 23.6
                                                          : this.state.firstName
                                                              .length === 12
                                                            ? 22
                                                            : this.state
                                                                .firstName
                                                                .length === 13
                                                              ? 20.5
                                                              : 19.2)
                                  : 300 - this.state.firstName.length * 18.1
                                : 30,
                            textTransform: "uppercase",
                            fontWeight: "bold",
                            textAlign: "center",
                            color: "black",
                            width: isMobile ? "100%" : 400
                          }}
                          onKeyPress={event => {
                            if (event.key === "Enter") {
                              {
                                /* if (event.target.value) {
                              if (this.state.firstname_complete) {
                                this.handleSubmit();
                              } else {
                                this.setState({ firstname_complete: true });
                              }
                            } else {
                              this.setState({
                                open: true,
                                alertmsg: "Enter first Name"
                              });
                            }
                          } */
                              }
                              this.handleSubmit();
                            }
                          }}
                          onChange={event => {
                            this.setState({
                              firstName: event.target.value,
                              show_error: false
                            });
                          }}
                        />

                        {this.state.firstname_complete && (
                          <div className=" lastname" style={styles.slideup}>
                            <input
                              className="autoscale_username bcd_secondname"
                              type="text"
                              value={this.state.lastName}
                              placeholder="Last Name"
                              autoFocus="true"
                              autoComplete="off"
                              maxLength={15}
                              style={{
                                fontSize:
                                  this.state.lastName.length > 0
                                    ? this.state.lastName.length < 15
                                      ? this.state.lastName.length < 3
                                        ? 330 -
                                          this.state.lastName.length *
                                            (this.state.lastName.length * 30)
                                        : 300 -
                                          this.state.lastName.length *
                                            (this.state.lastName.length === 3
                                              ? 55
                                              : this.state.lastName.length === 4
                                                ? 50
                                                : this.state.lastName.length ===
                                                  5
                                                  ? 42
                                                  : this.state.lastName
                                                      .length === 6
                                                    ? 38
                                                    : this.state.lastName
                                                        .length === 7
                                                      ? 34
                                                      : this.state.lastName
                                                          .length === 8
                                                        ? 31
                                                        : this.state.lastName
                                                            .length === 9
                                                          ? 28
                                                          : this.state.lastName
                                                              .length === 10
                                                            ? 25.5
                                                            : this.state
                                                                .lastName
                                                                .length === 11
                                                              ? 23.6
                                                              : this.state
                                                                  .lastName
                                                                  .length === 12
                                                                ? 22
                                                                : this.state
                                                                    .lastName
                                                                    .length ===
                                                                  13
                                                                  ? 20.5
                                                                  : 19.2)
                                      : 300 - this.state.lastName.length * 18.1
                                    : 30,

                                textTransform: "uppercase",
                                backgroundColor:
                                  this.state.lastName.length === 0
                                    ? "black"
                                    : "black",
                                raised: "true",
                                fontWeight: 200,
                                textAlign: "center",
                                fontFamily: "Lato",
                                color: "#ffffff"
                              }}
                              onKeyPress={event => {
                                if (event.key === "Enter") {
                                  if (event.target.value) {
                                    if (this.state.lastname_complete) {
                                      this.handleSubmit();
                                    } else {
                                      this.setState({
                                        lastname_complete: true
                                      });
                                    }
                                  } else {
                                    this.setState({
                                      show_error: true,
                                      error: "Enter Last Name"
                                    });
                                  }
                                }
                              }}
                              onChange={event =>
                                this.setState({
                                  lastName: event.target.value,
                                  show_error: false
                                })
                              }
                            />
                            <hr
                              style={{
                                backgroundColor:
                                  this.state.lastName.length === 0
                                    ? "black"
                                    : "black",
                                height: 4,
                                //width: isMobile ? "100%":"400",
                                border: 0,
                                marginTop: 0
                              }}
                              className="bcd_hr"
                            />
                          </div>
                        )}
                        {this.state.lastname_complete && (
                          <div
                            className="test email_class"
                            style={styles.slideup}
                          >
                            <input
                              className="autoscale_username email_detail"
                              //readOnly={this.state.read_email==true?"true":"false"}
                              type="text"
                              id="input"
                              value={this.state.email}
                              autoFocus="true"
                              autoComplete="off"
                              onKeyPress={event => {
                                if (event.key === "Enter") {
                                  this.handleSubmit();
                                }
                              }}
                              style={{
                                textAlign: "center",
                                width: isMobile ? "100%" : 400
                              }}
                              placeholder="Enter Your Email"
                              onChange={event =>
                                this.setState({
                                  email: event.target.value,
                                  show_error: false
                                })
                              }
                            />
                            <br />
                          </div>
                        )}
                        {isMobile && (
                          <div className="button_next_continue_div">
                            {!this.state.lastname_complete && (
                              <div className="next_btn_div">
                                <button
                                  onClick={() => this.handleSubmit()}
                                  className=""
                                >
                                  Next
                                </button>
                              </div>
                            )}
                            {this.state.lastname_complete && (
                              <div className="continue_btn_div">
                                <button
                                  onClick={() => this.handleSubmit()}
                                  className=""
                                >
                                  Continue
                                </button>
                              </div>
                            )}
                          </div>
                        )}
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </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>
            )}
            {!isMobile && (
              <div className="arrow_hidden">
                <div className="row">
                  <div className="col-md-6 col-lg-6 ">
                    <img
                      src={api.image_path + "prev_arrow_one.jpg"}
                      width="40"
                      className="next_icon next_left"
                      onClick={() => {
                        this.props.history.push("/");
                      }}
                    />
                  </div>
                </div>
                <div>
                  <img
                    src={api.image_path + "next_arrow_one.png"}
                    width="40"
                    className="next_icon next_right"
                    onClick={() => {
                      this.handleSubmit();
                    }}
                  />
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    );
  }
}

const styles = {
  labelStyle: { color: "rgba(224, 214, 214, 0.87)", fontSize: 14 },
  slideup: {
    animation: "x 1s",
    animationName: Radium.keyframes(slideInUp, "slideup")
  },
  slideInRight: {
    animation: "x 1s",
    animationName: Radium.keyframes(slideInRight, "slideInRight")
  }
};

export default basicContactDetails;
