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 cookie from "react-cookies";
let path;
var jwt_decode = require("jwt-decode");
var base64 = require("base-64");
class Login extends Component {
  constructor(props) {
    super(props);
    let is_contest = localStorage.getItem("contest");
    // localStorage.setItem("refered_by_id","email|5b507ac9a6803a9191926620")
    // localStorage.setItem("refered_contest_id","15")
    console.log("refered_by_id", cookie.load("refered_by_id"));
    console.log("refered_contest_id", cookie.load("refered_contest_id"));
    console.log("user_id", cookie.load("user_id"));
    console.log("relative_user_id", cookie.load("relative_user_id"));
    console.log("check_user_id", cookie.load("check_user_id"));
    cookie.save("userId", "userId", { path: "/" });

    if (typeof is_contest === "undefined") {
    } else if (is_contest === "true") {
      let redirect = this.props.history;
      let contest_id = cookie.load("refered_contest_id");
      console.log(redirect);
      // redirect.push("/Contest/" + contest_id + "/" + userid);
    }

    this.state = {
      email: "",
      open: false,
      alertmsg: "",
      is_login: localStorage.getItem("login_failed_email") ? true : false,
      login: "",
      loader: false,
      nocontest: false,
      push_contest: false,
      show_error: false,
      error: ""
    };
    this.handleSubmit.bind(this);
  }

  handleSubmit = () => {
    let redirect = this.props.history;

    if (this.state.email === "" || !this.state.email) {
      this.setState({ show_error: true, error: "Email should not be empty" });
    } 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;

      if (email != null) {
        email = email.replace('"', "");
        email.replace(/[`~!@#$%^&*()_|+\-=÷¿?;:'",.<>\\]/gi, "\\$&");
      }
      this.setState({ email: "" });
      let self = this;
      // Testing purpose QojjBgcvYKuRciNLarQZEMXwI4j2Jk24
      // Live purpose SHcHyNsbh1nUG8ffWEpVRlSa0nT686EZ
      let finalJson = {
        action: "login",
        client_id: api.login_key,
        connection: "email",
        email: email,
        send: "link",
        authParams: {
          scope: "openid"
        }
      };
      console.log("finaljson", finalJson);
      self.setState({ loader: true });
      axios
        .request({
          method: "post",
          url: api.react_request,
          data: JSON.stringify(finalJson)
        })
        .then(function(login_response) {
          console.log("login_response", login_response);
          if (login_response.status === 200) {
            if (
              login_response.data.error_description ===
              "Public signup is disabled"
            ) {
              localStorage.setItem("login_failed_email", email);
              self.setState({ loader: false });
              localStorage.setItem("current_state", "login_failed"),
                self.props.history.push("/login_failed");
            } else {
              self.setState({ loader: false });
              localStorage.setItem("current_state", "login_link_send");
              self.props.history.push("/login_link_send");
            }
          }
        })
        .catch(error => {
          self.setState({ loader: false });
          console.log("error", error);
          self.setState({ loader: false });
          self.setState({
            show_error: true,
            error: "Something Wrong... Please try Again"
          });
        });
    }
  };

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

  render() {
    return (
      <center>
        <div className="background-images">
          <div className="background_color">
            <StyleRoot>
              <div className="home_btn home_width" style={styles.slideInRight}>
                <div className="container-fluid">
                  <div style={styles.root}>
                    {this.state.loader && (
                      <center>
                        <CircularProgress
                          size={100}
                          style={{ color: "black", marginTop: "17%" }}
                        />
                      </center>
                    )}
                    <Dialog
                      style={{ textTransform: "capitalize" }}
                      actions={
                        <FlatButton
                          label="Close"
                          onClick={() =>
                            this.state.nocontest
                              ? (localStorage.setItem(
                                  "current_state",
                                  "set_relation"
                                ),
                                this.props.history.push("/set_relation"))
                              : this.handleClose()
                          }
                        />
                      }
                      modal={false}
                      open={this.state.open}
                    >
                      {this.state.alertmsg}
                    </Dialog>
                    <div>
                      {!this.state.loader && (
                        <div className="allpages_desktop_boxes_div">
                          <div className="row">
                            <p className="home_para homepage_para">LOGIN TO</p>
                          </div>
                          <div className="row">
                            <img
                              src={api.image_path + "familyone_logo.png"}
                              height="80px"
                            />
                          </div>
                          <div className="home_btn">
                            <input
                              className="email_text"
                              type="text"
                              value={this.state.email}
                              autoFocus="true"
                              onKeyPress={event => {
                                if (event.key === "Enter") {
                                  this.handleSubmit();
                                }
                              }}
                              style={{
                                backgroundColor: "transparent",
                                textAlign: "center"
                              }}
                              placeholder="Enter Your Email"
                              onChange={event =>
                                this.setState({
                                  email: event.target.value,
                                  show_error: false
                                })
                              }
                            />
                          </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>
                      )}

                      {this.state.is_login && (
                        <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>
                  </div>
                </div>
              </div>
            </StyleRoot>
          </div>
        </div>
      </center>
    );
  }
}

const styles = {
  button: { margin: 12 },
  slideInRight: {
    animation: "x 1s",
    animationName: Radium.keyframes(slideInRight, "slideInRight")
  }
};

export default Login;
