import React from "react";
import axios from "axios";
import Countdown from "react-countdown-now";
import CircularProgress from "@material-ui/core/CircularProgress";
import Drawer from "./drawer";
import Dialog from "material-ui/Dialog";
import FlatButton from "material-ui/FlatButton";
import api from "./api/api";
import cookie from "react-cookies";
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"));
    let user_id = [];
    let temp_id = cookie.load("user_id");
    user_id = temp_id.split("|");
    if (
      localStorage.getItem("current_state") !== "social_share" )  {
        this.props.history.push("/menu_page");
      }
    var contest_id = localStorage.getItem("contest_id");
    // console.log("public url: ", window.location.href);
    var path = window.location.protocol + "//" + window.location.host;

    console.log("window", window.location);
    this.state = {
      is_active: localStorage.getItem("login_is_active") == 1 ? true : false,
      user_id: user_id[1],
      contest_id: contest_id,
      contest: [],

      open: false,
      alertmsg: "",
      googleplus_url: "",
      share_link: "",
      fb_url: "",
      twiter_url: "",
      push_contest: false
    };
    this.link_contest = this.link_contest.bind();
    this.handleFb = this.handleFb.bind();
    this.handleTwitter = this.handleTwitter.bind();
    this.handleGPlus = this.handleGPlus.bind();
  }
  componentDidMount() {
    this.setState({ loader: true });
    let self = this;
    let contest_detail;
    var get_link = {
      action: "get_contest_sharelink",
      contest_id: this.state.contest_id,
      enter_link:
        window.location.origin +
        localStorage.getItem("pathname") +
        "?Contest/" +
        self.state.contest_id +
        "/"
    };
    console.log("get_link", get_link);
    axios
      .request({
        method: "POST",
        url: api.react_request,
        data: JSON.stringify(get_link)
      })
      .then(response => {
        console.log("response", response);
        contest_detail = localStorage.getItem("contest_detail");
        console.log("contest_detail", JSON.parse(contest_detail));
        self.setState({ contest: JSON.parse(contest_detail) });
        self.setState({
          share_link: response.data.share_link + this.state.user_id
        });
        self.setState({
          fb_url:
            "http://www.facebook.com/sharer.php?u=" +
            response.data.share_link.facebook +
            "/" +
            this.state.user_id
        });
        self.setState({
          twiter_url:
            "https://twitter.com/share?url=" +
            response.data.share_link.twitter +
            "/" +
            this.state.user_id
        });
        self.setState({
          googleplus_url:
            "https://plus.google.com/share?url=" +
            response.data.share_link.google +
            "/" +
            this.state.user_id
        });
        self.setState({
          loader:
            false
        });

        if (self.state.contest.contest_id === "22") {
          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: "email|"+cookie.load("refered_by_id"),
            child_ids: child_ids,
            is_social: 0,
            contest_id: localStorage.getItem("contest_id"),
            similac: {
              privacy_time: localStorage.getItem("privacy_time"),
              personal_info_time: localStorage.getItem("personal_info_time"),
              research_comm_time: localStorage.getItem("research_comm"),
              source: "LIST_FAM_ONE",
              club: "Similac",
              delloite: "NULL",
              partner_id: "sim-familyone-acq1",
              language: "E",
              privacy: 1,
              personal_info: 1,
              research_comm: 1
            }
          };
          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... Please try again"
              });
            });
        }
      })
      .catch(function(error) {
        console.log("error", error);
        self.setState({ loader: false });
        self.setState({
          open: true,
          alertmsg: "Something Wrong... Please try again"
        });
      });
  }

  handleFb = () => {
    console.log("activated");
    window.open(this.state.fb_url, "_blank");
  };

  handleTwitter = () => {
    console.log("activated");
    window.open(this.state.twiter_url, "_blank");
  };

  handleGPlus = () => {
    console.log("activated");
    window.open(this.state.googleplus_url, "_blank");
  };

  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) {
            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 (self.state.push_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")));
              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(function(error) {
        console.log("error", error);
        self.setState({ loader: false });
        self.setState({
          open: true,
          alertmsg: "Something Wrong... Please try again"
        });
      });
  };

  render() {
    return (
      <div className="container1">
        <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 && (
              <div className="rowContainerContest contest_header_div 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>
                )}
                {this.state.contest.image &&
                <div className="row contest_image_div">
                  <img
                    src={api.image_path + this.state.contest.image}
                    width="100%"
                  />
                </div>
                }
                <div className="socialshare_whitebgdiv">
                  {this.state.contest.is_contest !== "1" && (
                    <div className="row">
                      <p style={{ color: "grey" }}>
                        Share these freebie's to your friends & family
                      </p>
                      <p style={{ color: "grey" }}>extra entry point</p>
                    </div>
                  )}
                  {this.state.contest.is_contest === "1" && (
                    <div className="row">
                      <p style={{ color: "grey" }}>
                        Social Share, for each person that enters,you'll get an
                      </p>
                      <p style={{ color: "grey" }}>extra entry point</p>
                    </div>
                  )}
                  <div className="row socialshare_btndiv">
                    <a
                      onClick={() => {
                        this.handleFb();
                      }}
                    >
                      <img src={api.image_path + "fb1.png"} width="100px" />
                    </a>
                    <a
                      onClick={() => {
                        this.handleTwitter();
                      }}
                    >
                      <img
                        src={api.image_path + "twitter.png"}
                        width="100px"
                        style={{ paddingLeft: 3 }}
                      />
                    </a>&nbsp;
                    <a
                      onClick={() => {
                        this.handleGPlus();
                      }}
                    >
                      <img
                        src={api.image_path + "googleplus.png"}
                        width="100px"
                      />
                    </a>&nbsp;
                  </div>
                </div>
                <div className="row">
                  <button
                    className="donebtn"
                    onClick={() => {
                      this.state.contest.is_contest === "1"
                        ? localStorage.setItem("current_state", "share")
                        : localStorage.setItem("current_state", "family");
                      this.props.history.push({
                        pathname:
                          this.state.contest.is_contest === "1"
                            ? "/share"
                            : this.link_contest()
                      });
                    }}
                  >
                    Done
                  </button>
                </div>
              </div>
            )}
        </center>
      </div>
    );
  }
}

export default Share;
