import React, { Component } from "react";
import axios from "axios";
import Dialog from "material-ui/Dialog";
import FlatButton from "material-ui/FlatButton";
import { slideInUp, slideInRight } from "react-animations";
import Radium, { StyleRoot } from "radium";
import CircularProgress from "@material-ui/core/CircularProgress";
import api from "./api/api";
import Drawer from "./drawer";
import ListItemSecondaryAction from "@material-ui/core/ListItemSecondaryAction";
import Switch from "@material-ui/core/Switch";
import cookie from 'react-cookies'
class Unsubscribe extends Component {
  constructor(props) {
    super(props);
    console.log("Unsubscribe");
    // if (
    //   localStorage.getItem("current_state") !== "connect" ||
    //   localStorage.getItem("user_id") == "" ||
    //   localStorage.getItem("user_id") == "undefined" ||
    //   typeof localStorage.getItem("user_id") == undefined
    // ) {
    //   this.props.history.push("/");
    // }
    this.state = {
      open: false,
      relative_email: "",
      relation_exist: false,
      add_new_relation: false,
      alertmsg: "",
      first_name: "",
      lastName: "",
      firstName: "",
      checked1: true,
      checked2: true,
      loader: false,
      is_active: localStorage.getItem("login_is_active") == 1 ? true : false,
      relative_data: [],
      sender_name: "",
      reciever_id: ""
    };
    // this.handleUnsubscribe = this.handleUnsubscribe.bind(this);
    // this.handleUnsubscribeSender = this.handleUnsubscribeSender.bind(this);
    this.handleDone = this.handleDone.bind(this);
  }

  componentDidMount = () => {
    let self = this;

    console.log(
      "unsubscribe_reciever",
      localStorage.getItem("unsubscribe_reciever")
    );
    console.log(
      "unsubscribe_sender",
      localStorage.getItem("unsubscribe_sender")
    );
    // if (localStorage.getItem("user_email")) {
    let getUserInfo = {
      action: "get_information",
      user_id: localStorage.getItem("unsubscribe_sender")
    };
    self.setState({ loader: true });
    console.log("getUserInfo", getUserInfo);
    //self.setState({ loader: true });
    axios
      .request({
        url: api.react_request,
        method: "POST",
        data: JSON.stringify(getUserInfo)
      })
      .then(function(getUserInfoResponse) {
        console.log("getUserInfoResponse", getUserInfoResponse);
        self.setState({
          sender_name:
            getUserInfoResponse.data.user_metadata.first_name +
            " " +
            getUserInfoResponse.data.user_metadata.last_name,
          relative_data: getUserInfoResponse.data.user_metadata.relation,
          sender_id: getUserInfoResponse.data.user_id,
          loader: false
        });
      })

      .catch(error => {
        console.log("error", error);
        //self.setState({ loader: false });
        self.setState({
          open: true,
          alertmsg: "Something Wrong... Please try again later"
        });
      });
    // }
  };

  handleDone = () => {
    let self = this;
    console.log("handleDone");
    if (this.state.checked1 === true) {
      if (this.state.checked2 === true) {
        console.log("both true");
        console.log("handleUnsubscribe", this.state.relative_data);
        let reciever_id = "";
        this.state.relative_data.forEach(element => {
          if (
            element.member_email ===
            localStorage.getItem("unsubscribe_reciever")
          ) {
            this.setState({ reciever_id: element.user_id });
            reciever_id = element.user_id;
          }
        });
        console.log("reciever", localStorage.getItem("unsubscribe_reciever"));
        let update = {
          action: "update",
          user_id: reciever_id,
          user_metadata: {
            family_one_contest_mail: false
          }
        };

        console.log("update", update);

        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);
            console.log("handleUnsubscribeSender", self.state.relative_data);
            let relative_data = self.state.relative_data;
            let temp_relative = [];
            relative_data.forEach(element => {
              if (
                element.member_email ===
                localStorage.getItem("unsubscribe_reciever")
              ) {
                console.log("match");
                element.email_send = false;
              }
              temp_relative.push(element);
            });
            console.log("temp_relative", temp_relative);
            self.setState({ relative_data: temp_relative });
            let update = {
              action: "update",
              user_id: localStorage.getItem("unsubscribe_sender"),
              user_metadata: {
                relation: temp_relative
              }
            };

            console.log("update", update);
            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);
                self.props.history.push("/");
              })
              .catch(error => {
                console.log("error", error);
                self.setState({ loader: false });
                self.setState({
                  open: true,
                  alertmsg: "Something Wrong... Please try again later"
                });
              });
          })
          .catch(error => {
            console.log("error", error);
            self.setState({ loader: false });
            self.setState({
              open: true,
              alertmsg: "Something Wrong... Please try again later"
            });
          });
      } else {
        console.log("checked1 true");
        console.log("handleUnsubscribeSender", self.state.relative_data);
        let relative_data = self.state.relative_data;
        let temp_relative = [];
        relative_data.forEach(element => {
          if (
            element.member_email ===
            localStorage.getItem("unsubscribe_reciever")
          ) {
            console.log("match");
            element.email_send = false;
          }
          temp_relative.push(element);
        });
        console.log("temp_relative", temp_relative);
        self.setState({ relative_data: temp_relative });
        let update = {
          action: "update",
          user_id: localStorage.getItem("unsubscribe_sender"),
          user_metadata: {
            relation: temp_relative
          }
        };

        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);
            self.props.history.push("/");
          })
          .catch(error => {
            console.log("error", error);
            self.setState({ loader: false });
            self.setState({
              open: true,
              alertmsg: "Something Wrong... Please try again later"
            });
          });
      }
    } else if (this.state.checked2 === true) {
      console.log("handleUnsubscribe", self.state.relative_data);
      let reciever_id = "";
      self.state.relative_data.forEach(element => {
        if (
          element.member_email === localStorage.getItem("unsubscribe_reciever")
        ) {
          self.setState({ reciever_id: element.user_id });
          reciever_id = element.user_id;
        }
      });
      console.log("reciever", localStorage.getItem("unsubscribe_reciever"));
      let update = {
        action: "update",
        user_id: reciever_id,
        user_metadata: {
          family_one_contest_mail: false
        }
      };

      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.removeItem("unsubscribe_reciever");
          self.props.history.push("/");
        })
        .catch(error => {
          console.log("error", error);
          self.setState({ loader: false });
          self.setState({
            open: true,
            alertmsg: "Something Wrong... Please try again later"
          });
        });
    } else {
      console.log("nothing true");
      self.props.history.push("/");
    }
  };

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

  

  handleChange = name => event => {
    this.setState({ [name]: event.target.checked });
  };

  render() {
    return (
      <div className="bcd_header_div_margin index_page_header">
        <div className="allpages_desktop_boxes_div index_pt">
          {this.state.is_active && <Drawer prop={this.props} />}
          <StyleRoot>
            <div className="home_btn home_width" style={styles.slideInRight}>
              <div className="container-fluid">
                {this.state.loader && (
                  <CircularProgress
                    size={100}
                    style={{ color: "black", marginTop: "17%" }}
                  />
                )}
                <Dialog
                  style={{ textTransform: "capitalize" }}
                  actions={
                    <FlatButton
                      label="Close"
                      labelStyle={{ color: "#000" }}
                      onClick={() => {
                        this.handleClose();
                      }}
                    />
                  }
                  modal={false}
                  open={this.state.open}
                  //onRequestClose={this.handleClose}
                >
                  {this.state.alertmsg}
                </Dialog>
                {!this.state.loader && (
                  <div>
                    <p
                      style={styles.slideInUp}
                      className="title3_contestshare  text-center"
                    >
                      Contest share notification settings:
                    </p>
                    <p
                      style={styles.slideInUp}
                      className="title3_contestshare1  text-center"
                    >
                      Send me contest notifications from:
                    </p>
                    <div className="cs_relativename_div">
                      <p className="cs_div_para">{this.state.sender_name}</p>
                      <div className="cs_relativename_div_second unsuscribe_div">
                        <p>Off</p>
                        <ListItemSecondaryAction style={styles.inputproperty}>
                          <Switch
                            checked={this.state.checked1}
                            onChange={this.handleChange("checked1")}
                            //onChange={this.handleChange('checked1')}
                          />
                        </ListItemSecondaryAction>
                        <p className="on_para">On</p>
                      </div>
                    </div>
                    <div className="cs_relativename_div">
                      <p className="cs_div_para">Anyone</p>
                      <div className="cs_relativename_div_second unsuscribe_div">
                        <p>Off</p>
                        <ListItemSecondaryAction style={styles.inputproperty}>
                          <Switch
                            checked={this.state.checked2}
                            onChange={this.handleChange("checked2")}
                          />
                        </ListItemSecondaryAction>
                        <p className="on_para">On</p>
                      </div>
                    </div>
                    <div className="m_t70">
                      <a
                        onClick={() => {
                          this.handleDone();
                        }}
                        className="white-btn px20 py20 unsuscribe_whitebtn"
                      >
                        <i className="unsus_i">
                          <img
                            src={api.image_path+"prev_arrowBkup.jpg"}
                            alt=""
                            title=""
                            width="30"
                          />
                        </i>
                        <span>All done! Show me what's new </span>
                      </a>
                    </div>
                    <div className="mt70" />
                  </div>
                )}
              </div>
            </div>
          </StyleRoot>
        </div>
      </div>
    );
  }
}

const styles = {
  labelStyle: { color: "rgba(224, 214, 214, 0.87)", fontSize: 14 },
  slideup: {
    animation: "x 1s",
    animationName: Radium.keyframes(slideInUp, "slideup")
  },
  slideInRight: {
    animation: "x 1s",
    animationName: Radium.keyframes(slideInRight, "slideInRight")
  },
  inputproperty: {
    position: "relative",
    transform: "translateY(-25%)"
  }
};

export default Unsubscribe;
