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 relatedEntrantOrientation extends Component {
  constructor(props) {
    super(props);
    if (
      localStorage.getItem("current_state") !== "related_entrant_orientation" )  {
        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_name:
        localStorage.getItem("related_first_name") +
        " " +
        localStorage.getItem("related_last_name"),
      familymemberdata: [],
      push_contest: false,
      is_active: localStorage.getItem("login_is_active") == 1 ? true : false
    };
    this.linkContest = this.linkContest.bind(this);
    this.myContest = this.myContest.bind(this);
  }

  handleClose = () => {
    this.setState({ open: false });
  };
  linkContest = () => {
    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.length > 0) {
          if (response.data.length !== 0) {
            let freebies=[];
            let contest=[];
            self.setState({ loader: false });
            localStorage.setItem("current_state", "contest");
            localStorage.setItem(
              "contest_array",
              JSON.stringify(response.data)
            );
            localStorage.setItem(
              "contest_detail",
              JSON.stringify(response.data[0])
            );
            localStorage.setItem("contest_index", 0);
            console.log(JSON.parse(localStorage.getItem("contest_array")));
            localStorage.setItem("user", "related");
            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 {
              localStorage.setItem("current_state", "contest"),
              self.props.history.push(
                "/Contest/" +
                  response.data[0]._id +
                  "/" +
                  cookie.load("user_id")
              );
            }
            
          } 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"
        });
      })
  };

  myContest = () => {
    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.length > 0) {
          if (response.data.length !== 0) {
            let contest = [];
            response.data.forEach(element => {
              console.log("element", element);
              if (element.direct == 0) {
                console.log("nothing");
              } else {
                self.setState({ push_contest: true });
                contest.push(element);
              }
            });
            console.log("contest", contest);
            if (self.state.push_contest) {
              self.setState({ loader: false });
              localStorage.setItem("current_state", "contest");
              localStorage.setItem("contest_array", JSON.stringify(contest));
              localStorage.setItem("contest_index", 0);
              localStorage.setItem(
                "contest_detail",
                JSON.stringify(contest[0])
              );
              console.log(JSON.parse(localStorage.getItem("contest_array")));
              localStorage.setItem("user", "related");
              if(contest.length===0){
                self.setState({ loader: false });
                localStorage.setItem("current_state", "no_contest"),
                self.props.history.push("/no_contest");
              }
              else{
                localStorage.setItem("current_state", "contest"),
                self.props.history.push(
                  "/Contest/" +
                    contest[0]._id +
                    "/" +
                    cookie.load("user_id")
                );
              }
            }
          } 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}
        >
          {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">
                  <img
                    src={api.image_path+"familyoneContest.png"}
                    alt=""
                    title=""
                    className="related_orientation_img_first"
                  />
                </div>
                <div className="someonepage_header_div_first">
                  <img
                    src={api.image_path+"related_orientation.jpg"}
                    alt=""
                    title=""
                    className="related_orientation_img_second"
                  />
                </div>
              </div>
              <div className="someonepage_footer_div">
                <div className="someonepage_footer_div_second  reo_btn_share">
                  <button
                    style={{ backgroundColor: "#8037A3" }}
                    className="btn_FamilyShare reo_btnfamily_share"
                  >
                    Family<br /> Share
                  </button>&nbsp;&nbsp;&nbsp;
                  <button className="btn_SocialShare reo_btnsocial_share">
                    Social<br />Share
                  </button>
                </div>
                <div className="someonepage_footer_div_first  reo_text_pare">
                  <p className="family_friends_para">Family & Friends </p>
                  <p className="para_second">
                    Sometimes there are contests that we can't enter, but are
                    friends and family can. Even through we can't win ourselves,
                    we can still help our friends and family to win.
                  </p>
                </div>
                <div className="someonepage_footer_div_third">
                  <a
                    onClick={() => this.linkContest()}
                    className="white-btn px20 py40"
                  >
                    <span className="reo_span">
                      Help my family win !{" "}
                      <i>
                        <img
                          src={api.image_path+"next_arrow.jpg"}
                          alt=""
                          title=""
                          width="30"
                        />
                      </i>
                    </span>
                  </a>
                </div>
                <div className="reo_anchor_div">
                  {/* ye aayega idhar
              onClick={() => this.linkContest()}
               */}
                  <a onClick={() => this.myContest()}>
                    Skip,I don't want to help my family win
                  </a>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    );
  }
}
export default relatedEntrantOrientation;
