import React, { Component } from "react";
import FlatButton from "material-ui/FlatButton";
import Dialog from "material-ui/Dialog";
import { slideInRight, slideOutRight } from "react-animations";
import Radium from "radium";
import { FormControl } from "react-bootstrap";
import axios from "axios";
import Script from "react-load-script";
import CircularProgress from "@material-ui/core/CircularProgress";
import $ from "jquery";
import api from "./api/api";
import cookie from "react-cookies";
import { isMobile } from "react-device-detect";
import SelectField from "material-ui/SelectField";
import MenuItem from "material-ui/MenuItem";
import country from "./country/countries";
let countries = [];
class EditAddress extends Component {
  constructor(props) {
    super(props);

    console.log("session", localStorage.getItem("current_state"));
    console.log("is_active", localStorage.getItem("login_is_active"));
    console.log("user_id", cookie.load("user_id"));
    console.log(
      "edit_streetaddress",
      localStorage.getItem("edit_streetaddress")
    );
    if (localStorage.getItem("current_state") !== "edit_address") {
      this.props.history.push("/menu_page");
    }
    this.state = {
      address: "",
      addressLine2: localStorage.getItem("edit_address")
        ? localStorage.getItem("edit_address_line2")
        : "",
      streetAddress: localStorage.getItem("edit_address")
        ? localStorage.getItem("edit_streetaddress")
        : "",
      addressLine2Enable:
        localStorage.getItem("edit_address_line2").length > 0 ? true : false,
      city: localStorage.getItem("edit_address")
        ? localStorage.getItem("edit_city")
        : "",
      addressLine1: "",
      addressHint: true,
      state: localStorage.getItem("edit_address")
        ? localStorage.getItem("edit_state")
        : "",
      postalCode: localStorage.getItem("edit_address")
        ? localStorage.getItem("edit_zip_code")
        : "",
      open: false,
      alertmsg: "",
      value: 1,
      loader: false,
      country: "",
      check_country: "",
      is_active: localStorage.getItem("login_is_active") == 1 ? true : false,
      streetAddress_complete: true,
      addressLine2_complete: true,
      city_complete: true,
      state_complete: true,
      zipcode_complete: true,
      countries: "",
      signup: localStorage.getItem("previous") !== "login" ? true : false
    };
    this.handleSubmit.bind(this);
  }

  componentDidMount() {
    var country_arr = country;
    var script = document.createElement('script');
    script.src = "https://ws1.postescanada-canadapost.ca/js/addresscomplete-2.30.min.js?key=mm44-yz97-me83-uc98";
    script.addEventListener('load', function () {
      console.log("fsef")
      // resolve();
    });
    script.addEventListener('error', function (e) {
      // reject(e);
    });
    document.body.appendChild(script);
    countries = [];
    for (let i = 0; i < country_arr.length; i++) {
      countries.push(
        <MenuItem
          value={country_arr[i]}
          key={i + country_arr[i] + "country"}
          primaryText={country_arr[i]}
          style={{
            top: "auto",
            bottom: "100%"
          }}
        />
      );
    }
    console.log("temp_countries", countries);
    this.setState({ countries: countries });
    this.setState({
      country: localStorage.getItem("edit_address")
        ? localStorage.getItem("edit_country")
        : ""
    });
    if (localStorage.getItem("edit_country") === "Canada") {
      this.setState({ check_country: "CA" });
    }
    if (localStorage.getItem("imported") === 1) {
      let country_code;
      this.setState({ country: "Canada" });
      country_code = "CA";
      this.setState({ check_country: country_code });
    }
  }

  changeCountry = (event, index, value) => {
    let country_code;
    console.log("value", value);
    this.setState({ country: value });
    if (value === "Canada") {
      country_code = "CA";
      this.setState({ check_country: country_code });
    } else {
      country_code = "value";
      this.setState({ check_country: country_code });
    }
  };

  handleSubmit = (line1, city2, province2, postalcode2) => {
    let finalJson = this.state.finalJson;
    // let action = this.props.resetState;
    let redirect = this.props.history;

    if (
      line1.length == "" ||
      city2.length == "" ||
      province2.length == "" ||
      postalcode2.length == ""
    ) {
      console.log("here");
    } else {
      var self = this;
      finalJson = {
        action: "update",
        user_id: cookie.load("user_id"),
        user_metadata: {
          address: {
            addressLine1: line1,
            city: city2,
            addressLine2: this.state.addressLine2,
            state: province2,
            zipcode: postalcode2,
            country: this.state.country
          }
        }
      };
      console.log("finalJson", finalJson);
      this.setState({ loader: true });
      axios
        .request({
          url: api.react_request,
          method: "POST",
          data: JSON.stringify(finalJson)
        })
        .then(function(response) {
          console.log("response", response);
          if (response.status === 200) {
            console.log("response.status", response.status);
            self.setState({ loader: false });
            localStorage.setItem(
              "address",
              JSON.stringify(response.data.user_metadata.address)
            );
            // localStorage.removeItem("addressLine2");
            // localStorage.removeItem("addressLine1");
            // localStorage.removeItem("city");
            // localStorage.removeItem("state");
            // localStorage.removeItem("zipcode");
            localStorage.setItem("current_state", "edit"),
              self.props.history.push("/edit");
          } else {
            self.setState({ open: true, alertmsg: response.data.error });
            self.setState({ loader: false });
          }
        })
        .catch(error => {
          console.log("error", error);
          self.setState({ loader: false });
          self.setState({
            open: true,
            alertmsg: "Something Wrong... Please try again later"
          });
        });
    }
  };

  handleSubmitAddress = () => {
    let finalJson = this.state.finalJson;
    // let action = this.props.resetState;
    let redirect = this.props.history;
    // let address_check = 0;
    if (
      this.state.state &&
      this.state.postalCode &&
      this.state.city &&
      this.state.streetAddress
    ) {
    var self = this;
    finalJson = {
      action: "update",
      user_id: cookie.load("user_id"),
      user_metadata: {
        address: {
          addressLine1: this.state.streetAddress,
          city: this.state.city,
          addressLine2: this.state.addressLine2,
          state: this.state.state,
          zipcode: this.state.postalCode,
          country: this.state.country
        }
      }
    };
    this.setState({ loader: true });
    console.log("finalJson", finalJson);
    axios
      .request({
        url: api.react_request,
        method: "POST",
        data: JSON.stringify(finalJson)
      })
      .then(function(response) {
        if (response.data.user_id) {
          localStorage.setItem(
            "address",
            JSON.stringify(response.data.user_metadata.address)
          );
          self.setState({ loader: false });
          // localStorage.removeItem("addressLine2");
          // localStorage.removeItem("addressLine1");
          // localStorage.removeItem("city");
          // localStorage.removeItem("state");
          // localStorage.removeItem("zipcode");

          // if (localStorage.getItem("is_active") == 1) {
          //   localStorage.setItem("current_state","family")
          //   redirect.push("/family/");
          // } else {
          localStorage.setItem("current_state", "edit");
          redirect.push("/edit");
          // }
        } else {
          self.setState({ open: true, alertmsg: response.data.error });
          self.setState({ loader: false });
        }
      })
      .catch(error => {
        console.log("error", error);
        self.setState({ loader: false });
        self.setState({
          open: true,
          alertmsg: "Something Wrong... Please try again later"
        });
      });
    }
    else {
      console.log("not ok");
      if (this.state.streetAddress === "") {
        this.setState({ open: true, alertmsg: "Fill Street Address" });
      } else if (this.state.city === "") {
        this.setState({ open: true, alertmsg: "Fill City" });
      } else if (this.state.state === "") {
        this.setState({ open: true, alertmsg: "Fill State" });
      } else if (this.state.zipcode === "") {
        this.setState({ open: true, alertmsg: "Fill Zipcode" });
      }
    }
  };

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

  handleChange = (event, index, value) => {
    this.setState({ value });
  };

  render() {
    return (
      <center>
        <div className="bcd_header_div_margin">
          <div className="allpages_desktop_boxes_div infoicon_paddingdiv">
            <div className="background-images">
              <div className="background_color">
                <div className="test" style={styles.slideInRight}>
                  <div className="containerfluid">
                    <div style={styles.root}>
                      {this.state.loader && (
                        <CircularProgress
                          size={100}
                          style={{ color: "black", marginTop: "17%" }}
                        />
                      )}
                      <Dialog
                        actions={
                          <FlatButton
                            label="Close"
                            labelStyle={{ color: "#000" }}
                            onClick={this.handleClose.bind(this)}
                          />
                        }
                        modal={false}
                        open={this.state.open}
                        onRequestClose={this.handleClose}
                      >
                        {this.state.alertmsg}
                      </Dialog>
                      {!this.state.loader && (
                        <div>
                          <div className="info_icon_div">
                            <img
                              src={api.image_path + "info1.png"}
                              alt="info_img"
                              className="info_img"
                              onClick={() => {
                                localStorage.setItem("info", "edit_address"),
                                  localStorage.setItem(
                                    "current_state",
                                    "information"
                                  ),
                                  this.props.history.push("/information");
                              }}
                            />
                          </div>
                          <div className="fma_house_div_logo">
                            <img
                              src={api.image_path + "house.png"}
                              width="300px"
                              height="100%"
                            />
                          </div>
                        </div>
                      )}
                      <form>
                        {!this.state.loader && (
                          <div
                            style={{
                              display:
                                this.state.check_country === "CA" &&
                                this.state.country === "Canada"
                                  ? "block"
                                  : "none"
                            }}
                          >
                            <div className="test">
                              <div className="">
                                <FormControl
                                  className="address_text add_uppercase"
                                  name="line1"
                                  id="line12"
                                  type="text"
                                  autoComplete="off"
                                  value={this.state.streetAddress}
                                  autoFocus={true}
                                  inputRef={ref => {
                                    this.line1 = ref;
                                    if (
                                      typeof this.line1 !== "undefined" &&
                                      this.line1
                                    ) {
                                      console.log("this", this.line1.value);
                                    }
                                  }}
                                  style={{ fontWeight: 300 }}
                                  placeholder="Enter Your Address"
                                  onChange={event => {
                                    this.setState({
                                      streetAddress: event.target.value
                                    });
                                  }}
                                />
                              </div>

                              {this.state.addressLine2Enable && (
                                <div>
                                  <FormControl
                                    className="address_text add_uppercase"
                                    type="text"
                                    name="line2"
                                    id="line22"
                                    value={this.state.addressLine2}
                                    placeholder="address line 2"
                                    autoFocus={this.state.addressLine2Enable}
                                    autoComplete="off"
                                    inputRef={ref => {
                                      this.line2 = ref;
                                    }}
                                    onKeyPress={event => {
                                      if (event.key === "Enter") {
                                        if (event.target.value) {
                                          this.handleSubmit(
                                            this.line1.value,
                                            this.city2.value,
                                            this.province2.value,
                                            this.postalcode2.value
                                          );
                                        }
                                      }
                                    }}
                                    onChange={event =>
                                      this.setState({
                                        addressLine2: event.target.value
                                      })
                                    }
                                  />
                                </div>
                              )}
                              {this.province2 &&
                                !this.state.addressLine2Enable &&
                                (this.line1 && this.line1.value != "") && (
                                  <div style={{ marginTop: -5 }}>
                                    <label
                                      onClick={event => {
                                        this.setState({
                                          addressLine2Enable: true,
                                          city: this.city2.value,
                                          state: this.province2.value,
                                          postalCode: this.postalcode2.value
                                        });
                                      }}
                                      className="addline2"
                                    >
                                      +Add line 2
                                    </label>
                                  </div>
                                )}
                              <div style={{ marginTop: -10 }}>
                                <FormControl
                                  className="address_text add_uppercase"
                                  type="text"
                                  value={this.state.city}
                                  autoFocus={false}
                                  autoComplete="off"
                                  name="city"
                                  id="city2"
                                  inputRef={ref => {
                                    this.city2 = ref;
                                  }}
                                  placeholder="city"
                                  onChange={event =>
                                    this.setState({ city: event.target.value })
                                  }
                                />
                              </div>
                              <div style={{ marginTop: -10 }}>
                                <FormControl
                                  className="address_text add_uppercase "
                                  type="text"
                                  value={this.state.state}
                                  name="province"
                                  id="province2"
                                  autoFocus={false}
                                  autoComplete="off"
                                  maxLength={2}
                                  inputRef={ref => {
                                    this.province2 = ref;
                                  }}
                                  placeholder="province"
                                  onChange={event =>
                                    this.setState({ state: event.target.value })
                                  }
                                />
                              </div>
                              <div style={{ marginTop: -10 }}>
                                <FormControl
                                  className="address_text add_uppercase "
                                  type="text"
                                  value={this.state.postalCode}
                                  placeholder="Postal Code"
                                  autoFocus={false}
                                  autoComplete="off"
                                  name="postalcode"
                                  id="postalcode2"
                                  inputRef={ref => {
                                    this.postalcode2 = ref;
                                  }}
                                  onChange={event =>
                                    this.setState({
                                      postalCode: event.target.value,
                                      backgroundcoler: "pink"
                                    })
                                  }
                                />
                              </div>
                            </div>
                          </div>
                        )}

                        {!this.state.loader && (
                          <div
                            style={{
                              display:
                                this.state.check_country !== "CA" &&
                                this.state.country !== "CA" &&
                                this.state.country !== ""
                                  ? "block"
                                  : "none"
                            }}
                          >
                            <div className="test">
                              <div className="padding_top">
                                <div>
                                  <FormControl
                                    className="address_text add_uppercase "
                                    name="streetAddress"
                                    type="text"
                                    value={this.state.streetAddress}
                                    autoFocus={true}
                                    autoComplete="off"
                                    style={{ fontWeight: 300 }}
                                    placeholder="Enter Your Address"
                                    onChange={event => {
                                      this.setState({
                                        streetAddress: event.target.value
                                      });
                                      //console.log("dsdsdss");
                                    }}
                                    onKeyPress={event => {
                                      if (event.key === "Enter") {
                                        if (event.target.value) {
                                          console.log("this", this.state);
                                          this.setState({
                                            streetAddress_complete: true
                                          });
                                        } else {
                                          console.log("this", this.state);
                                          this.setState({
                                            open: true,
                                            alertmsg: "Enter Street Address"
                                          });
                                        }
                                      }
                                    }}
                                  />
                                </div>

                                {this.state.addressLine2Enable && (
                                  <div>
                                    <FormControl
                                      className="address_text add_uppercase"
                                      type="text"
                                      name="addressLine2"
                                      value={this.state.addressLine2}
                                      placeholder="Address line 2"
                                      style={{ fontWeight: 300 }}
                                      autoComplete="off"
                                      autoFocus={this.state.addressLine2Enable}
                                      onKeyPress={event => {
                                        if (event.key === "Enter") {
                                          if (event.target.value) {
                                            this.handleSubmitAddress();
                                          }
                                        }
                                      }}
                                      onChange={event =>
                                        this.setState({
                                          addressLine2: event.target.value
                                        })
                                      }
                                    />
                                  </div>
                                )}
                                {!this.state.addressLine2Enable &&
                                  this.state.streetAddress_complete && (
                                    <div style={{ marginTop: -11 }}>
                                      <label
                                        style={{ fontWeight: 300 }}
                                        onClick={event => {
                                          this.setState({
                                            addressLine2Enable: true
                                          });
                                        }}
                                        className="addline2"
                                      >
                                        +Add line 2
                                      </label>
                                    </div>
                                  )}
                                {this.state.streetAddress_complete && (
                                  <div style={{ marginTop: -9 }}>
                                    <FormControl
                                      className="address_text add_uppercase"
                                      type="text"
                                      value={this.state.city}
                                      style={{ fontWeight: 300 }}
                                      autoFocus={
                                        this.state.streetAddress_complete
                                      }
                                      name="city"
                                      autoComplete="off"
                                      onKeyPress={event => {
                                        if (event.key === "Enter") {
                                          if (event.target.value) {
                                            this.setState({
                                              city_complete: true
                                            });
                                          } else {
                                            this.setState({
                                              open: true,
                                              alertmsg: "Enter city"
                                            });
                                          }
                                        }
                                      }}
                                      placeholder="City"
                                      onChange={event =>
                                        this.setState({
                                          city: event.target.value
                                        })
                                      }
                                    />
                                  </div>
                                )}

                                <div style={{ marginTop: -9 }}>
                                  {this.state.city_complete && (
                                    <FormControl
                                      className="address_text  add_uppercase"
                                      type="text"
                                      value={this.state.state}
                                      style={{
                                        width: 300
                                      }}
                                      name="province"
                                      autoFocus={this.state.city_complete}
                                      placeholder="State"
                                      autoComplete="off"
                                      onChange={event =>
                                        this.setState({
                                          state: event.target.value
                                        })
                                      }
                                      onKeyPress={event => {
                                        if (event.key === "Enter") {
                                          if (event.target.value) {
                                            this.setState({
                                              state_complete: true
                                            });
                                          } else {
                                            this.setState({
                                              open: true,
                                              alertmsg: "Enter State"
                                            });
                                          }
                                        }
                                      }}
                                    />
                                  )}
                                </div>
                                <div style={{ marginTop: -9 }}>
                                  {this.state.state_complete && (
                                    <FormControl
                                      className="address_text add_uppercase"
                                      type="text"
                                      value={this.state.postalCode}
                                      placeholder="Postal Code"
                                      style={{
                                        width: 300
                                      }}
                                      autoComplete="off"
                                      autoFocus={this.state.state_complete}
                                      name="postalcode"
                                      onKeyPress={event => {
                                        if (event.key === "Enter") {
                                          if (event.target.value) {
                                            this.handleSubmitAddress();
                                          }
                                        }
                                      }}
                                      onChange={event =>
                                        this.setState({
                                          postalCode: event.target.value
                                        })
                                      }
                                    />
                                  )}
                                </div>
                              </div>
                            </div>
                          </div>
                        )}
                      </form>
                      {!this.state.loader && (
                        <SelectField
                          hintText="Select Country"
                          // value={value}
                          className="address_text add_uppercase"
                          onChange={this.changeCountry.bind(this)}
                          style={{
                            marginTop:
                              this.state.country !== "" ? "-14px" : "30px"
                          }}
                          value={this.state.country}
                          className="userBirthdate_ddm select_countery_ddl sc_textuppercase"
                        >
                          {countries}
                        </SelectField>
                      )}
                      {!this.state.loader && (
                        <center>
                          {/* {isMobile && (
                      <div className="button_next_continue_div">
                        {this.state.check_country !== "CA" && (
                          <div className="next_btn_div">
                            <button
                              onClick={() => this.changeEmail()}
                              className=""
                            >
                              Next
                            </button>
                          </div>
                        )}
                        <div className="continue_btn_div">
                          <button
                            onClick={() => this.changeEmail()}
                            className=""
                          >
                            Continue
                          </button>
                        </div>
                      </div>
                    )} */}
                          {isMobile && (
                            <div className="button_next_continue_div">
                              {!this.state.lastname_complete && (
                                <div className="next_btn_div">
                                  <button
                                    onClick={event => {
                                      this.state.check_country === "CA"
                                        ? this.handleSubmit(
                                            this.line1.value,
                                            this.city2.value,
                                            this.province2.value,
                                            this.postalcode2.value
                                          )
                                        : this.handleSubmitAddress();
                                    }}
                                    className=""
                                  >
                                    Next
                                  </button>
                                </div>
                              )}
                              {/* {this.state.lastname_complete && (
                            <div className="continue_btn_div">
                              <button
                                onClick={() => this.handleSubmit()}
                                className=""
                              >
                                Continue
                              </button>
                            </div>
                          )} */}
                            </div>
                          )}
                          {!isMobile && (
                            <div
                              className="fma_btndone_div fma_btndone_new"
                              style={{ paddingBottom: 10 }}
                            >
                              <button
                                className=""
                                onClick={event => {
                                  this.state.check_country === "CA"
                                    ? this.handleSubmit(
                                        this.line1.value,
                                        this.city2.value,
                                        this.province2.value,
                                        this.postalcode2.value
                                      )
                                    : this.handleSubmitAddress();
                                }}
                              >
                                Done
                              </button>
                            </div>
                          )}
                        </center>
                      )}
                    </div>
                  </div>
                  {!this.state.loader && (
                    <div className="row">
                      <div className="col-md-6 col-lg-6 ">
                        <img
                          src={api.image_path + "next_arrow_one.png"}
                          width="40"
                          className="next_icon next_right"
                          onClick={event => {
                            this.state.check_country === "CA"
                              ? this.handleSubmit(
                                  this.line1.value,
                                  this.city2.value,
                                  this.province2.value,
                                  this.postalcode2.value
                                )
                              : this.handleSubmitAddress();
                          }}
                        />
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>
      </center>
    );
  }
}

const styles = {
  labelStyle: {
    color: "rgba(224, 214, 214, 0.87)",
    fontSize: 14
  },
  slideInRight: {
    animation: "x 1s",
    animationName: Radium.keyframes(slideInRight, "slideInRight")
  },
  slideOutRight: {
    animation: "x 1s",
    animationName: Radium.keyframes(slideOutRight, "slideOutRight")
  }
};

export default EditAddress;
