import React from "react";
import { Label } from "react-bootstrap";
import axios from "axios";
import api from "./api/api";
import { isMobile } from "react-device-detect";
import Dialog from "material-ui/Dialog";
import FlatButton from "material-ui/FlatButton";
import { FormControl } from "react-bootstrap";
import CircularProgress from "@material-ui/core/CircularProgress";
import Drawer from "./drawer";
import Script from "react-load-script";
import cookie from 'react-cookies'
// import Autocomplete from './fullMailingAddress'

let user_id;
class edit extends React.Component {
  constructor(props) {
    console.log("connect", sessionStorage.getItem("hey"));
    user_id = cookie.load("user_id");
    super(props);
    if (
      localStorage.getItem("current_state") !== "edit" ) {
        this.props.history.push("/menu_page");
      }
    this.state = {
      open: false,
      alertmsg: "",
      loader: false,
      is_active: localStorage.getItem("login_is_active") == 1 ? true : false,
      nocontest: false,
      child_data: [],
      first_name: "",
      last_name: "",
      email: "",
      alt_email: "",
      addressLine1: "",
      firstname_complete: false,
      lastname_complete: false,
      alternative_email: "",
      streetAddress: "",
      addressLine2: "",
      city: "",
      state: "",
      postalCode: "",
      checked: false,
      is_alt_email: false,
      edit_name: false,
      edit_address: false,
      check_country: "",
      country:""
    };
    this.handleChildEdit = this.handleChildEdit.bind(this);
    this.handleUserData = this.handleUserData.bind(this);
  }

  componentDidMount = () => {
    console.log("here");
    let country_code;
    var self = this;

    country_code = localStorage.getItem("country_code");
    console.log(country_code);
    self.setState({ check_country: country_code });
    this.setState({ first_name: localStorage.getItem("first_name") });
    // console.log("localStorage.getItem", localStorage.getItem("first_name"));
    this.setState({ last_name: localStorage.getItem("last_name") });
    this.setState({
      firstname_complete: localStorage.getItem("first_name") ? true : false
    });
    this.setState({
      lastname_complete: localStorage.getItem("last_name") ? true : false
    });
    this.setState({ email: localStorage.getItem("user_email") });
    this.setState({
      alt_email:
        localStorage.getItem("alternative_email") !== "undefined"
          ? localStorage.getItem("alternative_email")
          : ""
    });
    if (
      typeof localStorage.getItem("address") !== undefined &&
      localStorage.getItem("address") !== null &&
      localStorage.getItem("address") !== "undefined"
    ) {
      let address = JSON.parse(localStorage.getItem("address"));
      // console.log("address", address);
      this.setState({
        streetAddress: address.addressLine1,
        addressLine2: address.addressLine2,
        city: address.city,
        state: address.state,
        postalCode: address.zipcode,
        country:address.country
      });
    }
    // console.log("localStorage.getItem", localStorage.getItem("child_data"));
    if (
      typeof localStorage.getItem("child_data") !== undefined &&
      localStorage.getItem("child_data") !== null &&
      localStorage.getItem("child_data") !== "undefined"
    ) {
      let child_data = [];
      JSON.parse(localStorage.getItem("child_data")).forEach(element => {
        let temp_family = {};
        let getChildJson = {
          action: "get_information",
          user_id: element.child_id
        };
        let self = this;
        self.setState({ loader: true });
        axios
          .request({
            method: "POST",
            url: api.react_request,
            data: JSON.stringify(getChildJson)
          })
          .then(function(child_data_response) {
            // console.log("child_response");
            let date = new Date();
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            month = month < 10 ? "0" + month : month;
            let day = date.getDate();
            day = day < 10 ? "0" + day : day;
            let today = year + "-" + month + "-" + day;

            if (child_data_response.data.user_metadata.boy_or_girl == "Girl") {
              if (
                child_data_response.data.user_metadata.baby_birthday > today
              ) {
                temp_family["is_expecting"] = true;
                temp_family["colorname"] = "rgb(247, 154, 201)";
              } else {
                temp_family["is_expecting"] = false;
                temp_family["colorname"] = "rgb(247, 57, 147)";
              }
            } else if (
              child_data_response.data.user_metadata.boy_or_girl == "Boy"
            ) {
              if (
                child_data_response.data.user_metadata.baby_birthday > today
              ) {
                temp_family["is_expecting"] = true;
                temp_family["colorname"] = "rgb(141, 215, 224)";
              } else {
                temp_family["is_expecting"] = false;
                temp_family["colorname"] = "rgb(7, 217, 252)";
              }
            } else {
              if (
                child_data_response.data.user_metadata.baby_birthday > today
              ) {
                temp_family["is_expecting"] = true;
                temp_family["colorname"] = "rgb(179, 179, 179)";
              }
            }
            temp_family["gender"] =
              child_data_response.data.user_metadata.boy_or_girl;
            temp_family["date"] =
              child_data_response.data.user_metadata.baby_birthday;
            child_data.push(temp_family);
            self.setState({ loader: false });

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

  handleChildEdit = () => {
    localStorage.setItem("edit_child_date", this.state.child_data.date);
    localStorage.setItem(
      "edit_child_is_expecting",
      this.state.child_data.is_expecting
    );
    localStorage.setItem("relation_with_children1", "both");
    localStorage.setItem("edit_child_gender", this.state.child_data.gender);
    localStorage.setItem("is_edit", "true");
    console.log("is_edit", localStorage.getItem("is_edit"));
    localStorage.setItem("current_state", "set_relation"),
      this.props.history.push("/set_relation");
  };

  handleUserData = () => {
    console.log("here");
    if (this.state.first_name === "") {
      this.setState({ open: true, alertmsg: "Enter First Name" });
    } else if (this.state.last_name === "") {
      this.setState({ open: true, alertmsg: "Enter Last Name" });
    } else if (this.state.email === "" || !this.state.email) {
      this.setState({ open: true, alertmsg: "Enter Email" });
    } else if (
      !this.state.email.match(/^([a-zA-Z0-9_.-]+@([\w-]+\.)+[\w-]{2,10})?$/)
    ) {
      this.setState({ open: true, alertmsg: "Email is not valid" });
    } else if (this.state.streetAddress === "") {
      this.setState({ open: true, alertmsg: "Enter Street Address" });
    } else if (this.state.city === "") {
      this.setState({ open: true, alertmsg: "Enter City" });
    } else if (this.state.state === "") {
      this.setState({ open: true, alertmsg: "Enter Province" });
    } else if (this.state.postalCode === "") {
      this.setState({ open: true, alertmsg: "Enter Postal Code" });
    } else {
      let email = this.state.email;
      let firstName = this.state.firstName;
      let lastName = this.state.lastName;

      if (email != null) {
        email = email.replace('"', "");
        email.replace(/[`~!@#$%^&*()_|+\-=÷¿?;:'",.<>\\]/gi, "\\$&");
      }
      if (firstName != null) {
        firstName = firstName.replace('"', "");
        firstName.replace(/[`~!@#$%^&*()_|+\-=÷¿?;:'",.<>\\]/gi, "\\$&");
      }
      if (lastName != null) {
        lastName = lastName.replace('"', "");
        lastName.replace(/[`~!@#$%^&*()_|+\-=÷¿?;:'",.<>\\]/gi, "\\$&");
      }
      this.setState({ loader: true });
      // this.setState({ email: "", firstName: "", lastName: "" });
      localStorage.setItem("first_name", this.state.first_name);
      localStorage.setItem("last_name", this.state.last_name);
      console.log("handleUserData");
      let self = this;
      let editJson = {
        action: "update",
        user_id: cookie.load("user_id"),
        email: this.state.checked
          ? this.state.alternative_email
          : this.state.email,
        user_metadata: {
          first_name: this.state.first_name.charAt(0).toUpperCase() + this.state.first_name.substr(1),
          last_name: this.state.last_name.charAt(0).toUpperCase() + this.state.last_name.substr(1),
          alternative_email: this.state.checked
            ? this.state.email
            : this.state.alternative_email
        }
      };
      console.log("editJson", editJson);
      axios
        .request({
          url: api.react_request,
          method: "POST",
          data: JSON.stringify(editJson)
        })
        .then(function(response) {
          if (response) {
            self.setState({ loader: false });
            console.log("response", response);
            localStorage.setItem(
              "first_name",
              response.data.user_metadata.first_name
            );
            localStorage.setItem(
              "last_name",
              response.data.user_metadata.last_name
            );
            localStorage.setItem("user_email", response.data.email);
            localStorage.setItem(
              "address",
              JSON.stringify(response.data.user_metadata.address)
            );
            localStorage.setItem("current_state", "menu_page"),
            self.props.history.push("/menu_page");
          }
        })
        .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 });
  };

  render() {
    return (
      <div className="edit_page">
      <Script url="https://ws1.postescanada-canadapost.ca/js/addresscomplete-2.30.min.js?key=ru81-ta19-fh86-fy38" />
        {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="edit_page_header">
            <div className="edit_page_header_div">
              <div className="edit_page_header_div_first">
                <button
                  onClick={() => {
                    this.setState({ edit_name: true, edit_address: false });
                  }}
                  className="btn_editname"
                >
                  {this.state.edit_name ? "Done" : "Edit"}
                </button>
                {!this.state.edit_name && <p>{this.state.first_name}</p>}
                {this.state.edit_name && (
                  <input
                    value={this.state.first_name}
                    onChange={event => {
                      this.setState({ first_name: event.target.value });
                    }}
                    className="autoscale_username email_detail"
                    type="text"
                    autoFocus="true"
                    autoComplete="off"
                    onKeyPress={event => {
                      if (event.key === "Enter") {
                        if (event.target.value.length > 0) {
                          this.handleUserData();
                        }
                      }
                    }}
                    style={{
                      width: isMobile ? "100%" : 400,
                      color: "#969696"
                    }}
                    placeholder="Enter Your First Name"
                  />
                )}

                {!this.state.edit_name && <p>{this.state.last_name}</p>}
                {this.state.edit_name && (
                  <input
                    value={this.state.last_name}
                    onChange={event => {
                      this.setState({ last_name: event.target.value });
                    }}
                    className="autoscale_username email_detail"
                    type="text"
                    autoFocus="true"
                    autoComplete="off"
                    onKeyPress={event => {
                      if (event.key === "Enter") {
                        if (event.target.value.length > 0) {
                          this.handleUserData();
                        }
                      }
                    }}
                    style={{
                      width: isMobile ? "100%" : 400,
                      color: "#969696"
                    }}
                    placeholder="Enter Your Last Name"
                  />
                )}
                {!this.state.edit_name && (
                  <p className="email">{this.state.email}</p>
                )}
                {this.state.edit_name && (
                  <input
                    value={this.state.email}
                    onChange={event => {
                      this.setState({ email: event.target.value });
                    }}
                    className="autoscale_username email_detail"
                    type="text"
                    autoFocus="true"
                    autoComplete="off"
                    onKeyPress={event => {
                      if (event.key === "Enter") {
                        if (event.target.value.length > 0) {
                          this.handleUserData();
                        }
                      }
                    }}
                    style={{
                      width: isMobile ? "100%" : 400,
                      color: "#969696"
                    }}
                    placeholder="Enter Your Email"
                  />
                )}
                {!this.state.is_alt_email && (
                  <p className="email" style={{ display: "flex" }}>
                    <span>+</span>
                    <a
                      onClick={() => {
                        this.setState({ is_alt_email: true });
                      }}
                    >
                      Use alternative email for communication
                    </a>
                  </p>
                )}
                {this.state.is_alt_email && (
                  <input
                    value={this.state.alternative_email}
                    onChange={event => {
                      this.setState({ alternative_email: event.target.value });
                    }}
                    className="autoscale_username email_detail"
                    type="text"
                    autoFocus="true"
                    autoComplete="off"
                    onKeyPress={event => {
                      if (event.key === "Enter") {
                        if (event.target.value.length > 0) {
                          this.handleUserData();
                        }
                      }
                    }}
                    style={{
                      width: isMobile ? "100%" : 400,
                      color: "#969696"
                    }}
                    placeholder="Enter Your Alternative Email"
                  />
                )}
              </div>
            </div>
            <div className="edit_page_header_div edit_page_header_div_bgcolor">
              <div className="edit_page_header_div_first">
                <button
                  onClick={() => {
                    //this.setState({ edit_address: true, edit_name: false });
                    localStorage.setItem("edit_address","true"), 
                    localStorage.setItem("edit_address_line2",this.state.addressLine2),
                    localStorage.setItem("edit_streetaddress",this.state.streetAddress),
                    localStorage.setItem("edit_city",this.state.city),
                    localStorage.setItem("edit_state",this.state.state),
                    localStorage.setItem("edit_zip_code",this.state.postalCode),
                    localStorage.setItem("edit_country",this.state.country),
                    localStorage.setItem("current_state", "edit_address"),
                    this.props.history.push("/edit_address");
                  }}
                  className="btn_editname"
                >
                  {this.state.edit_address ? "Done" : "Edit Address"}
                </button>
                <p className="address">Address:</p>
                {!this.state.edit_address && (
                  <Label className="email street_addresss">
                    {this.state.streetAddress}
                  </Label>
                )}
                

                {this.state.edit_address &&
                  this.state.check_country === "CA" && (
                    <input
                      value={this.state.streetAddress}
                      onChange={event => {
                        this.setState({ streetAddress: event.target.value });
                      }}
                      className="autoscale_username email_detail"
                      type="text"
                      autoFocus="true"
                      autoComplete="off"
                      onKeyPress={event => {
                        if (event.key === "Enter") {
                          if (event.target.value.length > 0) {
                            this.handleUserData();
                          }
                        }
                      }}
                      style={{
                        width: isMobile ? "100%" : 400,
                        color: "#969696"
                      }}
                      placeholder="Street Address"
                    />
                  )}
                {!this.state.edit_address && (
                  <Label className="email">
                    {this.state.addressLine2 == ""
                      ? "   "
                      : this.state.addressLine2}
                  </Label>
                )}
                {this.state.edit_address &&
                  this.state.check_country === "CA" && (
                    <input
                      value={this.state.addressLine2}
                      onChange={event => {
                        this.setState({ addressLine2: event.target.value });
                      }}
                      className="autoscale_username email_detail"
                      type="text"
                      autoFocus="true"
                      autoComplete="off"
                      onKeyPress={event => {
                        if (event.key === "Enter") {
                          if (event.target.value.length > 0) {
                            this.handleUserData();
                          }
                        }
                      }}
                      style={{
                        width: isMobile ? "100%" : 400,
                        color: "#969696"
                      }}
                      placeholder="Address Line 2"
                    />
                  )}
                {!this.state.edit_address && (
                  <span className="span">
                    <Label className="email">{this.state.city},</Label>
                    <Label className="email_first">{this.state.state}</Label>
                  </span>
                )}
                {this.state.edit_address &&
                  this.state.check_country === "CA" && (
                    <span className="span">
                      <input
                        value={this.state.city}
                        onChange={event => {
                          this.setState({ city: event.target.value });
                        }}
                        className="autoscale_username email_detail"
                        type="text"
                        autoFocus="true"
                        autoComplete="off"
                        onKeyPress={event => {
                          if (event.key === "Enter") {
                            if (event.target.value.length > 0) {
                              this.handleUserData();
                            }
                          }
                        }}
                        style={{
                          width: isMobile ? "100%" : 400,
                          color: "#969696"
                        }}
                        placeholder="City"
                      />
                      <input
                        value={this.state.state}
                        onChange={event => {
                          this.setState({ state: event.target.value });
                        }}
                        className="autoscale_username email_detail"
                        type="text"
                        autoFocus="true"
                        autoComplete="off"
                        onKeyPress={event => {
                          if (event.key === "Enter") {
                            if (event.target.value.length > 0) {
                              this.handleUserData();
                            }
                          }
                        }}
                        style={{
                          width: isMobile ? "100%" : 400,
                          color: "#969696"
                        }}
                        placeholder="Province"
                      />
                    </span>
                  )}

                {!this.state.edit_address && (
                  <Label className="email">{this.state.postalCode}</Label>
                )}
                {this.state.edit_address &&
                  this.state.check_country === "CA" && (
                    <input
                      value={this.state.postalCode}
                      onChange={event => {
                        this.setState({ postalCode: event.target.value });
                      }}
                      className="autoscale_username email_detail"
                      type="text"
                      autoFocus="true"
                      autoComplete="off"
                      onKeyPress={event => {
                        if (event.key === "Enter") {
                          if (event.target.value.length > 0) {
                            this.handleUserData();
                          }
                        }
                      }}
                      style={{
                        width: isMobile ? "100%" : 400,
                        color: "#969696"
                      }}
                      placeholder="Postal Code"
                    />
                  )}
              </div>
            </div>
            <div className="edit_page_header_div">
              <div className="edit_page_header_div_first child_info">
                <button
                  onClick={() => {
                    this.handleChildEdit();
                  }}
                  className="btn_editname"
                >
                  Edit Child Info
                </button>
                <p className="address">Child Info:</p>
                {this.state.child_data.map((child_data, index) => (
                  <div key={index}>
                    <Label className="email street_addresss">
                      {child_data.is_expecting ? "Expecting" : "Existing"}
                    </Label>
                    <Label className="email">{child_data.date}</Label>
                    <Label className="email">
                      {child_data.gender == "Un-known"
                        ? "Unknown"
                        : child_data.gender}
                    </Label>
                  </div>
                ))}
              </div>
            </div>
            <div className="edit_footer">
              <button
                className="donebtn"
                onClick={() => {
                  this.handleUserData();
                }}
              >
                Done
              </button>
            </div>
          </div>
        )}
      </div>
    );
  }
}
export default edit;
