import React, { Component } from "react";
import axios from "axios";
import CircularProgress from "@material-ui/core/CircularProgress";
import FlatButton from "material-ui/FlatButton";
import Dialog from "material-ui/Dialog";
import api from "./api/api";
import cookie from "react-cookies";
class account_activated extends Component {
  constructor(props) {
    super(props);
    if (localStorage.getItem("current_state") !== "account_activated") {
      this.props.history.push("/menu_page");
    }

    console.log("session", localStorage.getItem("current_state"));
    console.log("is_active", localStorage.getItem("login_is_active"));
    this.state = {
      loader: false,
      is_active: localStorage.getItem("login_is_active") == 1 ? true : false,
      open: false,
      alertmsg: "",
      nocontest: false,
      push_contest: false
    };
    this.handleClick = this.handleClick.bind(this);
  }

  //set link activated to 1 so that account activate won't come more than once
  componentDidMount = () => {
    
    let update = {
      action: "update",
      user_id: cookie.load("user_id"),
      link_activated: 1,
      user_metadata: {
        link_activated: 1
      }
    };

    console.log("update", update);
    let self = this;
    self.setState({ loader: true });
    axios
      .request({
        url: api.react_request,
        method: "POST",
        data: JSON.stringify(update)
      })
      .then(function(response) {
        self.setState({ loader: false });
        console.log("response", response);
        console.log(response.data);
      })
      .catch(error => {
        console.log("error", error);
        self.setState({ loader: false });
        self.setState({
          open: true,
          alertmsg: "Something Wrong... Please try again"
        });
      });
  };

  //close the dialog box
  handleClose = () => {
    this.setState({ open: false });
  };

  //handle the click on the personalise my account
  handleClick = () => {
    var self = this;

    console.log("user_id", cookie.load("user_id"));
    if (
      typeof cookie.load("user_id") !== undefined &&
      cookie.load("user_id") !== "undefined" &&
      cookie.load("user_id") !== "null" &&
      cookie.load("user_id") !== null &&
      cookie.load("user_id")
    ) {
      console.log("user_id", localStorage.getItem("address"));
      if (
        typeof cookie.load("relative_user_id") !== undefined &&
        cookie.load("relative_user_id") !== "undefined" &&
        cookie.load("relative_user_id") !== "null" &&
        cookie.load("relative_user_id") !== null &&
        cookie.load("relative_user_id")
      ) {
        console.log(
          "contest_id relative_user_id",
          cookie.load("relative_user_id")
        );
        localStorage.setItem("current_state", "connect");
        self.setState({ loader: false });
        self.props.history.push(
          "/Connect/" +
            cookie.load("relative_user_id") +
            "/" +
            cookie.load("relative_refered_by_user_id")
        );
      } else if (
        typeof localStorage.getItem("address") !== undefined &&
        localStorage.getItem("address") !== "undefined" &&
        localStorage.getItem("address") !== null
      ) {
        console.log("child_data", localStorage.getItem("child_data"));

        if (
          typeof cookie.load("relative_user_id") !== undefined &&
          cookie.load("relative_user_id") !== "undefined" &&
          cookie.load("relative_user_id") !== "null" &&
          cookie.load("relative_user_id") !== null &&
          cookie.load("relative_user_id")
        ) {
          console.log(
            "contest_id relative_user_id",
            cookie.load("relative_user_id")
          );
          localStorage.setItem("current_state", "connect");
          self.setState({ loader: false });
          self.props.history.push(
            "/Connect/" +
              cookie.load("relative_user_id") +
              "/" +
              cookie.load("relative_refered_by_user_id")
          );
        } else if (
          typeof cookie.load("refered_contest_id") !== undefined &&
          cookie.load("refered_contest_id") !== "undefined" &&
          cookie.load("refered_contest_id") !== "null" &&
          cookie.load("refered_contest_id") !== null &&
          cookie.load("refered_contest_id")
        ) {
          // response.data.contest_response.forEach(
          //   (element, index) => {
          //     if (
          //       element.contest_id ===
          //       cookie.load("refered_contest_id")
          //     ) {
          //       localStorage.setItem(
          //         "is_contest",
          //         element.is_contest
          //       );
          //       console.log("index", index);
          //       localStorage.setItem(
          //         "contest_array",
          //         JSON.stringify(response.data.contest_response)
          //       );
          //       localStorage.setItem(
          //         "contest_detail",
          //         JSON.stringify(element)
          //       );
          //       localStorage.setItem("contest_index", index);
          //     }
          //   }
          // );

          console.log("contest_id refered", cookie.load("refered_contest_id"));
          localStorage.setItem("current_state", "contest");
          self.setState({ loader: false });
          self.props.history.push(
            "/Contest/" +
              cookie.load("refered_contest_id") +
              "/" +
              cookie.load("user_id")
          );
        }

        //winning contest link
        else if (
          typeof cookie.load("winner_contest_id") !== undefined &&
          cookie.load("winner_contest_id") !== "undefined" &&
          cookie.load("winner_contest_id") !== "null" &&
          cookie.load("winner_contest_id") !== null &&
          cookie.load("winner_contest_id")
        ) {
          console.log("winner_contest_id", cookie.load("winner_contest_id"));
          let get_contest = {
            action: "getcontest",
            user_id: cookie.load("user_id"),
            contest_id: cookie.load("winner_contest_id")
          };
          console.log("get_contest", get_contest);
          axios
            .request({
              method: "POST",
              url: api.react_request,
              data: JSON.stringify(get_contest)
            })
            .then(function(get_contest_response) {
              console.log("response", get_contest_response);
              if (get_contest_response.data) {
                localStorage.setItem(
                  "is_contest",
                  get_contest_response.data[0].is_contest
                );
                localStorage.setItem(
                  "contest_array",
                  JSON.stringify(get_contest_response.data)
                );
                localStorage.setItem(
                  "contest_detail",
                  JSON.stringify(get_contest_response.data[0])
                );
                localStorage.setItem("contest_index", 0);
                if (get_contest_response.data[0]._id === "15") {
                  if (localStorage.getItem("product_id") === "2"|| localStorage.getItem("product_id") === 2) {
                    localStorage.setItem(
                      "current_state",
                      "product_orientation3"
                    );
                    self.props.history.push("/product_orientation3");
                  } else {
                    localStorage.setItem(
                      "current_state",
                      "product_orientation4"
                    );
                    self.props.history.push("/product_orientation4");
                  }
                } else {
                  localStorage.setItem("current_state", "won1"),
                    self.props.history.push("/won1");
                }
              } else {
                self.setState({
                  open: true,
                  alertmsg: "This Contest Is Not Live"
                });
              }
            })
            .catch(error => {
              console.log("error", error);
              self.setState({
                loader: false,
                alertmsg: "Something Wrong... Please try again later",
                open: true
              });
            });
        }

        //contest link
        else {
          var get_contest = {
            action: "getcontest",
            user_id: cookie.load("user_id"),
            is_active: localStorage.getItem("login_is_active")
          };
          console.log("get_contest", get_contest);
          self.setState({ loader: true });
          axios
            .request({
              method: "POST",
              url: api.react_request,
              data: JSON.stringify(get_contest)
            })
            .then(response => {
              console.log("response", response);
              if (response.status === 200) {
                let freebies = [];
                let contest = [];
                if (response.data.length !== 0) {
                  response.data.forEach(element => {
                    console.log("element", element);
                    if (element.direct == 0 || element.direct == "0") {
                      localStorage.setItem(
                        "current_state",
                        "related_entrant_orientation"
                      );
                      self.props.history.push("/related_entrant_orientation");
                    } else {
                      self.setState({ push_contest: true });
                    }
                    if (element.is_contest == 0) {
                      freebies.push(element);
                      self.setState({ is_freebies: true, freebies: freebies });
                    } else {
                      contest.push(element);
                      self.setState({ is_contest: true, contest: contest });
                    }
                  });
                  console.log("freebies", freebies);
                  console.log("contest", contest);

                  if (self.state.push_contest) {
                    localStorage.setItem(
                      "contest_array",
                      JSON.stringify(response.data)
                    );
                    console.log(
                      JSON.parse(localStorage.getItem("contest_array"))
                    );
                    localStorage.setItem(
                      "contest_detail",
                      JSON.stringify(response.data[0])
                    );
                    localStorage.setItem("contest_index", 0);
                    if (
                      typeof localStorage.getItem("need_to_claim") !==
                        undefined &&
                      localStorage.getItem("need_to_claim") !== "undefined" &&
                      localStorage.getItem("need_to_claim") !== "null" &&
                      localStorage.getItem("need_to_claim") !== null
                    ) {
                      console.log(
                        JSON.parse(localStorage.getItem("need_to_claim"))
                      );
                      localStorage.setItem("current_state", "won");
                      cookie.save(
                        "winner_contest_id",
                        JSON.parse(localStorage.getItem("need_to_claim_detail"))
                          .contest_id,
                        { path: "/" }
                      );
                      cookie.save(
                        "claim_for",
                        JSON.parse(localStorage.getItem("need_to_claim_detail"))
                          .id,
                        { path: "/" }
                      );
                      localStorage.setItem(
                        "need_to_claim_detail",
                        JSON.stringify(
                          JSON.parse(localStorage.getItem("need_to_claim"))[0]
                        )
                      );
                      self.props.history.push("/won");
                    } else {
                      if (freebies.length > 0) {
                        localStorage.setItem("current_state", "contest");
                        self.props.history.push(
                          "/Contest/" +
                            response.data[0]._id +
                            "/" +
                            cookie.load("user_id")
                        );
                      } else {
                        localStorage.setItem("current_state", "no_freebie");
                        self.props.history.push("/no_freebie");
                      }
                    }
                  }
                } else {
                  self.setState({ loader: false });

                  if (
                    typeof localStorage.getItem("child_data") !== undefined &&
                    localStorage.getItem("child_data") !== "undefined" &&
                    localStorage.getItem("child_data")
                  ) {
                    localStorage.setItem("current_state", "no_contest");
                    self.props.history.push("/no_contest");
                  } else {
                    self.setState({ loader: false });
                    localStorage.setItem("current_state", "set_relation");
                    self.props.history.push("/set_relation");
                  }
                }
              }
            })
            .catch(error => {
              console.log("error", error);
              self.setState({ loader: false });
              self.setState({
                open: true,
                alertmsg: "Something Wrong... Please Try Again Later"
              });
            });
        }
      } else {
        self.setState({ loader: false });
        localStorage.setItem("current_state", "full_mailing_address");
        self.props.history.push("/signup_step-2");
      }
    } else {
      self.setState({ loader: false });
      localStorage.setItem("current_state", "home");
      self.props.history.push("/");
    }
  };

  render() {
    return (
      <div className="page-bg">
        {/* {this.state.is_active && <Drawer prop={this.props} />} */}
        {!this.state.loader && <p className="title4 m_t20">Welcome to</p>}
        <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>
        {!this.state.loader && (
          <div className="welcome_img text-center">
            <img
              src={api.image_path + "family_one.png"}
              alt=""
              title=""
              className="max-w-200"
            />
          </div>
        )}
        <div className="inner_container">
          {this.state.loader && (
            <center>
              <br />
              <br />
              <br />
              <br />
              <br />
              <br />
              <CircularProgress
                size={100}
                style={{ color: "black", marginTop: "17%" }}
              />
            </center>
          )}
          {!this.state.loader && (
            <p className="m_t20 text-center">
              <img
                src={api.image_path + "activated_account_img.jpg"}
                alt=""
                title=""
                className="max-w-200-img"
              />
            </p>
          )}
          {!this.state.loader && (
            <p className="title2-wt text-center m_t20">Your Account is</p>
          )}
          {!this.state.loader && (
            <div className="welcome_img text-center">
              <img
                src={api.image_path + "activated.jpg"}
                alt=""
                title=""
                className="w-100 max-w-320"
              />
            </div>
          )}
          {!this.state.loader && (
            <div className="mt70">
              <a
                onClick={() => this.handleClick()}
                className="white-btn px20 py40"
              >
                <span>
                  Personalize my account{" "}
                  <i>
                    <img
                      src={api.image_path + "next_arrow.jpg"}
                      alt=""
                      title=""
                      width="30"
                    />
                  </i>
                </span>
              </a>
            </div>
          )}
          {!this.state.loader && <div className="mt70" />}
        </div>
      </div>
    );
  }
}
export default account_activated;
