import React from "react";
import api from "./api/api";
import axios from "axios";
import cookie from 'react-cookies'
import CircularProgress from "@material-ui/core/CircularProgress";
import Countdown from "react-countdown-now";
import Drawer from "./drawer";
import Dialog from "material-ui/Dialog";
import FlatButton from "material-ui/FlatButton";
class Share extends React.Component {
  constructor(props) {
    super(props);
    console.log("session", localStorage.getItem("current_state"));
    console.log("is_active", localStorage.getItem("login_is_active"));
    if (
      localStorage.getItem("current_state") !== "share" )  {
        this.props.history.push("/menu_page");
      }
    let contest_id = localStorage.getItem("contest_id");
    console.log("contest_id", contest_id);
    let user_id = cookie.load("user_id");
    console.log("user_id", user_id);
    this.state = {
      loader: false,
      user_id: user_id,
      contest_id: contest_id,
      open: false,
      alertmsg: "",
      contest: {},
      familymemberdata: [],
      is_active: localStorage.getItem("login_is_active") == 1 ? true : false,
      push_contest: false
    };
    this.link_contest = this.link_contest.bind();
    this.handleClickSocial = this.handleClickSocial.bind(this);
    this.handleClickFamily = this.handleClickFamily.bind(this);
  }
  componentDidMount() {
    localStorage.setItem("activity", "1");
    let contest_detail = localStorage.getItem("contest_detail");
    console.log("contest_detail", JSON.parse(contest_detail));
    this.setState({ contest: JSON.parse(contest_detail) });

    var self = this;
    let redirect = this.props.history;

    let child_ids = [];
    if (
      typeof localStorage.getItem("child_data") !== undefined &&
      localStorage.getItem("child_data") !== "undefined" &&
      localStorage.getItem("child_data") !== "null" &&
      localStorage.getItem("child_data") !== null &&
      localStorage.getItem("child_data")
    ) {
      console.log("child_ids", JSON.parse(localStorage.getItem("child_data")));
      JSON.parse(localStorage.getItem("child_data")).forEach(element => {
        let child_id = {};
        child_id.child_id = element.child_id;
        child_ids.push(child_id);
      });
      console.log("child_ids", child_ids);
    }
    console.log("refered_by_id", cookie.load("refered_by_id"))
    var join_contest = {
      action: "join_contest",
      perk_image: "perk_img.jpg",
      fname: localStorage.getItem("first_name"),
      is_contest: "1",
      to_email: localStorage.getItem("user_email"),
      user_id: cookie.load("user_id"),
      refered_user_id: cookie.load("refered_by_id"),
      child_ids: child_ids,
      is_social: 0,
      contest_id: localStorage.getItem("contest_id")
    };
    console.log("join_contest", join_contest);

    self.setState({ loader: true });
    axios
      .request({
        method: "POST",
        url: api.react_request,
        data: JSON.stringify(join_contest)
      })
      .then(function(json) {
        console.log("json", json);
        if (json.data.status == "OK") {
          self.setState({ loader: false });
          cookie.remove("refered_by_id");
          cookie.remove("refered_contest_id");
          // localStorage.setItem("current_state", "share");
          // redirect.push("/share");
        } 
        else{
          self.setState({ loader: false });
          cookie.remove("refered_by_id");
          cookie.remove("refered_contest_id");
        }
      })
      .catch(function(error) {
        console.log("error", error);
        self.setState({ loader: false });
        self.setState({ open: true, alertmsg: "Something Wrong" });
      });
  }

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

  link_contest = () => {
    var self = this;
    var get_contest = {
      action: "add_relation_update",
      update_info: {
        user_id: cookie.load("user_id"),
        user_metadata: {
          offer_orientation: 1
        }
      },
      get_contest: {
        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.contest_response.length > 0) {
          if (response.data.contest_response.length !== 0) {
            response.data.contest_response.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 (self.state.push_contest) {
              self.setState({ loader: false });
              localStorage.setItem("current_state", "contest");
              localStorage.setItem(
                "contest_array",
                JSON.stringify(response.data.contest_response)
              );
              localStorage.setItem(
                "contest_detail",
                JSON.stringify(response.data.contest_response[0])
              );
              localStorage.setItem("contest_index", 0);
              console.log(JSON.parse(localStorage.getItem("contest_array")));
              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.contest_response[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"
        });
      })
  };

  handleClickSocial = () => {
    let self = this;
    if (this.state.contest.contest_id === "15") {
      let finalJson = {
        action: "enable_share_flag",
        contest_id: 15,
        user_id: cookie.load("user_id")
      };
      self.setState({ loader: true });
      axios
        .request({
          method: "POST",
          url: api.react_request,
          data: JSON.stringify(finalJson)
        })
        .then(response => {
          self.setState({ loader: false });
          console.log("response", response);
          localStorage.setItem("current_state", "social_share"),
            self.props.history.push("/SocialShare");
        })
        .catch(error=>{
          console.log("error",error)
          self.setState({ loader: false });
        self.setState({
          show_error: true,
          error: "Something Wrong... Please try Again"
        });
        })
    } else {
      localStorage.setItem("current_state", "social_share"),
        self.props.history.push("/SocialShare");
    }
  };

  handleClickFamily = () => {
    let self = this;
    if (this.state.contest.contest_id === "15") {
      let finalJson = {
        action: "enable_share_flag",
        contest_id: 15,
        user_id: cookie.load("user_id")
      };
      self.setState({ loader: true });
      axios
        .request({
          method: "POST",
          url: api.react_request,
          data: JSON.stringify(finalJson)
        })
        .then(response => {
          self.setState({ loader: false });
          console.log("response", response);
          localStorage.setItem("orientation", "0");
          localStorage.setItem("current_state", "family_share");
          this.props.history.push({ pathname: "/family_share" });
        })
        .catch(error=>{
          console.log('error',error)
          self.setState({ loader: false });
        self.setState({
          show_error: true,
          error: "Something Wrong... Please try Again"
        });
        })
    } else {
      localStorage.setItem("orientation", "0");
      localStorage.setItem("current_state", "family_share");
      this.props.history.push({ pathname: "/family_share" });
    }
  };

  render() {
    // const { open } = this.state;
    return (
      <div>
        <center>
          {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 &&
            this.state.contest._id && (
              <div className="rowContainerContest contest_header_div">
                <div className="rowContainerContest socialshare ">
                  {this.state.contest.is_contest === 1 &&
                  <div className="row">
                    <div className="col-md-12">
                      <h4>
                        Ends in:&nbsp;<span>
                          <Countdown
                          daysInHours={true}
                            date={new Date(this.state.contest.expiry_date.replace(/-/g, "/"))}
                          />
                        </span>
                      </h4>
                    </div>
                  </div>
                  }
                  <div className="row contest_image_div">
                    <img
                      src={api.image_path+this.state.contest.image}
                      className="contest_image"
                    />
                  </div>
                  <div className="row">
                    <h4>Increase your chances</h4>
                  </div>
                  <div className="row sharebtn_div">
                    <button
                      style={{ backgroundColor: "#8037A3" }}
                      className="btn_FamilyShare"
                      onClick={() => {
                        localStorage.setItem("current_state", "family_share");
                        this.handleClickFamily();
                      }}
                    >
                      Family<br /> Share
                    </button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <button
                      className="btn_SocialShare"
                      onClick={() => {
                        localStorage.setItem("current_state", "social_share");
                        this.handleClickSocial();
                      }}
                    >
                      Social<br />Share
                    </button>
                  </div>
                  <br />
                  <div className="row">
                    <button
                      className="donebtn"
                      onClick={() => this.link_contest()}
                    >
                      Done
                    </button>
                  </div>
                </div>
              </div>
            )}
        </center>
      </div>
    );
  }
}

export default Share;
