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 Drawer from "./drawer";
import cookie from 'react-cookies'
class someoneOrientationScreen extends Component {
  constructor(props) {
    super(props);
    if (
      localStorage.getItem("current_state") !== "someone_orientation_screen")  {
        this.props.history.push("/menu_page");
      }
    this.state = {
      loader: false,
      user_id: cookie.load("user_id"),
      contest_id: localStorage.getItem("contest_id"),
      open: false,
      alertmsg: "",
      contest: {},
      related_first_name: localStorage.getItem("related_first_name"),
      related_name:
        localStorage.getItem("related_first_name") +
        " " +
        localStorage.getItem("related_last_name"),
      familymemberdata: [],
      freebies: [],
      contest: [],
      is_active: localStorage.getItem("login_is_active") == 1 ? true : false,
      push_contest: false
    };
    this.link_contest = this.link_contest.bind(this);
  }

  componentDidMount = () => {
    let update = {
      action: "update",
      user_id: cookie.load("user_id"),
      user_metadata: {
        someone_else_orientation: 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);
        localStorage.setItem(
          "someone_else_orientation",
          response.data.user_metadata.someone_else_orientation
        );
      })
      .catch(error => {
        console.log("error", error);
        self.setState({ loader: false });
        self.setState({
          open: true,
          alertmsg: "Something Wrong... Please try again later"
        });
      });
  };

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

  link_contest = () => {
    var self = this;
    var get_contest = {
      action: "getcontest",
      user_id: cookie.load("user_id"),
      is_active: localStorage.getItem("login_is_active")
    };
    console.log("get_contest", get_contest);
    this.setState({ loader: true });
    axios
      .request({
        method: "POST",
        url: api.react_request,
        data: JSON.stringify(get_contest)
      })
      .then(response => {
        console.log("response", response);
        if (response.data) {
          if (response.data.length > 0) {
            let freebies = [];
            let contest = [];
            response.data.forEach(element => {
              console.log("element", element);
              if (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)
              );
              localStorage.setItem(
                "contest_detail",
                JSON.stringify(response.data[0])
              );
              console.log(JSON.parse(localStorage.getItem("contest_array")));
              localStorage.setItem("current_state", "contest");
              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(
                  "need_to_claim_detail",
                  JSON.stringify(
                    JSON.parse(localStorage.getItem("need_to_claim"))[0]
                  )
                );
                localStorage.setItem("current_state", "won"),
                this.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 });
            localStorage.setItem("current_state", "no_contest"),
            self.props.history.push("/no_contest");
          }
        } else {
          self.setState({ loader: false });
          localStorage.setItem("current_state", "no_contest"),
          self.props.history.push("/no_contest");
        }
      })
      .catch(error=>{
        console.log("error",error)
        self.setState({ loader: false });
        self.setState({
          show_error: true,
          error: "Something Wrong... Please try Again"
        });
      })
  };
  render() {
    return (
      <div>
        {this.state.is_active && <Drawer prop={this.props} />}
        {this.state.loader && (
          <center>
            <CircularProgress
              size={100}
              style={{ color: "black", marginTop: "17%" }}
            />
          </center>
        )}
        <Dialog
          style={{ textTransform: "capitalize" }}
          actions={
            <FlatButton
              label="OK"
              labelStyle={{ color: "#000" }}
              onClick={() => this.handleClose()}
            />
          }
          modal={false}
          open={this.state.open}
          //onRequestClose={this.handleClose}
        >
          {this.state.alertmsg}
        </Dialog>
        {!this.state.loader && (
          <div className="bcd_header_div_margin orientation_first_div">
            <div className="allpages_desktop_boxes_div someone_header_first">
              <div className="someonepage_header_div">
                <div className="someonepage_header_div_first">
                  <p className="para_one">
                    There are contests and freebies waiting for{" "}
                    <span style={{ textTransform: "capitalize" }}>
                      {this.state.related_name}
                    </span>{" "}
                    to enter and redeem
                  </p>
                  <p className="para_second">
                    We're sending{" "}
                    <span style={{ textTransform: "capitalize" }}>
                      {this.state.related_first_name}
                    </span>{" "}
                    an invitation email from you. When{" "}
                    <span style={{ textTransform: "capitalize" }}>
                      {this.state.related_first_name}
                    </span>{" "}
                    registers, we'll let you know.
                  </p>
                  <img
                    src={api.image_path+"add-relation.jpg"}
                    alt=""
                    title=""
                    className="someone_img"
                  />
                </div>
              </div>
              <div className="someonepage_footer_div">
                <div className="someonepage_footer_div_first">
                  <p className="para_second">
                    Would you like to add more family members now?
                  </p>
                </div>
                <div className="someonepage_footer_div_second">
                  <button
                    onClick={() => {
                      localStorage.setItem("current_state", "family_share"),
                        localStorage.setItem("orientation", "1"),
                        this.props.history.push("/family_share");
                    }}
                    style={{ backgroundColor: "rgb(136, 98, 185)" }}
                    className="btn_FamilyShare btn_FamilyShare_sos"
                  >
                    +<br />
                    Family
                  </button>
                </div>
                <div className="someonepage_footer_div_first">
                  <p className="para_second">
                    You can always add more family members from My Family in the
                    side menu.
                  </p>
                </div>
                <div className="someonepage_footer_div_third">
                  <a
                    onClick={() => this.link_contest()}
                    className="white-btn px20 py40"
                  >
                    <span>
                      Continue{" "}
                      <i>
                        <img
                          src={api.image_path+"next_arrow.jpg"}
                          alt=""
                          title=""
                          width="30"
                        />
                      </i>
                    </span>
                  </a>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    );
  }
}
export default someoneOrientationScreen;
