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 api from "./api/api";
import { isMobile } from "react-device-detect";
import cookie from "react-cookies";
import SelectField from "material-ui/SelectField";
import MenuItem from "material-ui/MenuItem";
import country from "./country/countries";
import $ from "jquery";
let countries = [];
class fullMailingAddress 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("country", country);
    if (
      localStorage.getItem("current_state") !== "full_mailing_address")  {
        this.props.history.push("/menu_page");
      }
    this.state = {
      items: [],
      value: "",
      address: "",
      addressLine2:
        localStorage.getItem("login_is_active") === 0
          ? localStorage.getItem("addressLine2")
          : "",
      streetAddress:
        localStorage.getItem("login_is_active") === 0
          ? localStorage.getItem("addressLine1")
          : "",
      addressLine2Enable: false,
      city:
        localStorage.getItem("login_is_active") === 0
          ? localStorage.getItem("city")
          : "",

      addressHint: true,
      state:
        localStorage.getItem("login_is_active") === 0
          ? localStorage.getItem("state")
          : "",
      postalCode:
        localStorage.getItem("login_is_active") === 0
          ? localStorage.getItem("zipcode")
          : "",
      open: false,
      alertmsg: "",
      value: 1,
      loader: false,
      check_country: "",
      streetAddress_complete: false,
      addressLine2_complete: false,
      city_complete: false,
      state_complete: false,
      zipcode_complete: false,
      focus: true,
      show_error: false,
      country: "",
      error: "",
      countries:[],
      signup: localStorage.getItem("previous") !== "login" ? true : false
    };
    this.handleSubmit.bind(this);
    this.handleSubmitAddress.bind(this);
    this.handleChange.bind(this);
    this.changeCountry.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 });
    if(localStorage.getItem("imported")===1){
      let country_code;
      this.setState({ country: "Canada" });
        country_code = "CA";
        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 if(province2.length !== 2){
      self.setState({
        show_error: true,
        error: "Please Enter Province Code"
      });
    } 
    else {
      var self = this;
      finalJson = {
        action: "update",
        user_id: cookie.load("user_id"),
        user_metadata: {
          is_active: 1,
          address: {
            addressLine1: line1.charAt(0).toUpperCase() + line1.substr(1),
            city: city2.charAt(0).toUpperCase() + city2.substr(1),
            addressLine2: this.state.addressLine2.charAt(0).toUpperCase() + this.state.addressLine2.substr(1),
            state: province2.toUpperCase(),
            zipcode: postalcode2.charAt(0).toUpperCase() + postalcode2.substr(1),
            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");
            console.log(
              "login_is_active",
              localStorage.getItem("login_is_active")
            );
            if (localStorage.getItem("login_is_active") === 0) {
              const child_data_result = JSON.parse(
                localStorage.getItem("child_data")
              );
              if (child_data_result) {
                self.setState({ loader: false });
                localStorage.setItem("current_state", "family");
                redirect.push("/family");
              } else {
                self.setState({ loader: false });
                localStorage.setItem("current_state", "set_relation");
                redirect.push("/set_relation");
              }
            } else {
              self.setState({ loader: false });
              localStorage.setItem("current_state", "set_relation");
              redirect.push("/set_relation");
            }
          } else {
            self.setState({ show_error: true, error: response.data.error });
            self.setState({ loader: false });
          }
        })
        .catch(error => {
          console.log("error", error);
          self.setState({ loader: false });
          self.setState({
            show_error: true,
            error: "Something Wrong... Please try again"
          });
        });
    }
  };

  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: {
          is_active: 1,
          address: {
            addressLine1: this.state.streetAddress.charAt(0).toUpperCase() + this.state.streetAddress.substr(1),
            city: this.state.city.charAt(0).toUpperCase() + this.state.city.substr(1),
            addressLine2: this.state.addressLine2.charAt(0).toUpperCase() + this.state.addressLine2.substr(1),
            state: this.state.state.charAt(0).toUpperCase() + this.state.state.substr(1),
            zipcode: this.state.postalCode.toUpperCase(),
            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) {
          console.log("response", response);
          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");

          localStorage.setItem("current_state", "set_relation");
          redirect.push("/set_relation");

          // }
        })
        .catch(error => {
          console.log("error", error);
          self.setState({ loader: false });
          self.setState({
            show_error: true,
            error: "Something Wrong... Please try again"
          });
        });
    } else {
      console.log("not ok");
      if (this.state.streetAddress === "") {
        this.setState({ show_error: true, error: "Enter Street Address" });
      } else if (this.state.city === "") {
        this.setState({ show_error: true, error: "Enter City" });
      } else if (this.state.state === "") {
        this.setState({ show_error: true, error: "Enter Province" });
      } else if (this.state.postalCode === "") {
        this.setState({ show_error: true, error: "Enter Postal Code" });
      }
    }
  };

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

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

  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 });
    }
  };
  
  render() {
    return (
      <div className="bcd_header_div_margin">
        <div className="allpages_desktop_boxes_div index_pt fac_divheader">
          <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
                  style={{ textTransform: "capitalize" }}
                  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", "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>
                )}
                {!this.state.loader && (
                  <div
                    style={{
                      display:
                        this.state.check_country === "CA" &&
                        this.state.country === "Canada"
                          ? "block"
                          : "none"
                    }}
                  >
                    <div className="test">
                      <div className="padding_top">
                        <div className="">
                          <FormControl
                            className="address_text add_uppercase"
                            name="line1"
                            id="line12"
                            type="text"
                            autoComplete="off"
                            value={this.state.streetAddress}
                            autoFocus={this.state.check_country?true:false}
                            inputRef={ref => {
                              this.line1 = ref;
                              if (
                                typeof this.line1 !== "undefined" &&
                                this.line1
                              ) {
                                {
                                  /* this.setState({focus:false}) */
                                }
                                {
                                  /* console.log("this", this.line1.value); */
                                }
                              }
                            }}
                            style={{ fontWeight: 300 }}
                            placeholder="Enter Your Address"
                            onChange={event => {
                              this.setState({
                                streetAddress: event.target.value,
                                show_error: false
                              });
                            }}
                          />
                        </div>

                        {this.state.addressLine2Enable && (
                          <div>
                            <FormControl
                              className="address_text add_uppercase"
                              type="text"
                              name="line2"
                              id="line22"
                              autoComplete="off"
                              value={this.state.addressLine2}
                              placeholder="address line 2"
                              autoFocus={this.state.addressLine2Enable}
                              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,
                                  show_error: false
                                })
                              }
                            />
                          </div>
                        )}
                        {!this.state.addressLine2Enable &&
                          this.province2 &&
                          (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,
                                    streetAddress: this.line1.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,
                                show_error: false
                              })
                            }
                          />
                        </div>
                        <div style={{ marginTop: -10 }}>
                          <FormControl
                            className="address_text add_uppercase "
                            type="text"
                            autoComplete="off"
                            value={this.state.state}
                            name="province"
                            placeholder="Province"
                            id="province2"
                            autoFocus={false}
                            maxLength={2}
                            inputRef={ref => {
                              this.province2 = ref;
                              {
                                /* console.log("this.province", this.province2); */
                              }
                              if (
                                this.province2 !== null &&
                                typeof this.province2.value !== undefined
                              ) {
                                {
                                  /* console.log(
                                  "this.province2.value",
                                  this.province2.value
                                ); */
                                }
                              }
                            }}
                            onChange={event =>
                              this.setState({
                                state: event.target.value,
                                show_error: false
                              })
                            }
                          />
                        </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",
                                show_error: false
                              })
                            }
                          />
                        </div>
                      </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_address">
                        <div>
                          <FormControl
                            className="address_text add_uppercase "
                            name="streetAddress"
                            type="text"
                            value={this.state.streetAddress}
                            autoFocus={this.state.check_country?true:false}
                            autoComplete="off"
                            style={{
                              display:
                                this.state.check_country !== "CA" &&
                                this.state.country !== "CA" &&
                                this.state.country !== ""
                                  ? "initial"
                                  : "none",
                              fontWeight: 300
                            }}
                            placeholder="Enter Your Address"
                            onChange={event => {
                              this.setState({
                                streetAddress: event.target.value,
                                show_error: false
                              });
                              //console.log("dsdsdss");
                            }}
                            onKeyPress={event => {
                              if (event.key === "Enter") {
                                if (event.target.value) {
                                  if (this.state.streetAddress_complete) {
                                    this.handleSubmitAddress();
                                  } else {
                                    this.setState({
                                      streetAddress_complete: true
                                    });
                                  }
                                } else {
                                  {
                                    /* console.log("this", this.state); */
                                  }
                                  this.setState({
                                    show_error: true,
                                    error: "Enter Street Address"
                                  });
                                }
                              }
                            }}
                          />
                        </div>

                        {this.state.addressLine2Enable && (
                          <div>
                            <FormControl
                              className="address_text add_uppercase"
                              type="text"
                              name="addressLine2"
                              autoComplete="off"
                              value={this.state.addressLine2}
                              placeholder="Address line 2"
                              style={{
                              display:
                                this.state.check_country !== "CA" &&
                                this.state.country !== "CA" &&
                                this.state.country !== ""
                                  ? "initial"
                                  : "none",
                              fontWeight: 300,
                              marginTop:0
                            }}
                              autoFocus={this.state.addressLine2Enable}
                              onKeyPress={event => {
                                if (event.key === "Enter") {
                                  if (event.target.value) {
                                    this.handleSubmitAddress();
                                  }
                                }
                              }}
                              onChange={event =>
                                this.setState({
                                  addressLine2: event.target.value,
                                  show_error: false
                                })
                              }
                            />
                          </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: -10 }}>
                            <FormControl
                              className="address_text add_uppercase"
                              type="text"
                              value={this.state.city}
                              autoComplete="off"
                              style={{
                              display:
                                this.state.check_country !== "CA" &&
                                this.state.country !== "CA" &&
                                this.state.country !== ""
                                  ? "initial"
                                  : "none",
                              fontWeight: 300
                            }}
                              autoFocus={this.state.streetAddress_complete}
                              name="city"
                              onKeyPress={event => {
                                if (event.key === "Enter") {
                                  if (event.target.value) {
                                    if (this.state.city_complete) {
                                      this.handleSubmitAddress();
                                    } else {
                                      this.setState({ city_complete: true });
                                    }
                                  } else {
                                    this.setState({
                                      show_error: true,
                                      error: "Enter City"
                                    });
                                  }
                                }
                              }}
                              placeholder="City"
                              onChange={event =>
                                this.setState({
                                  city: event.target.value,
                                  show_error: false
                                })
                              }
                            />
                          </div>
                        )}

                        <div style={{ marginTop: -9 }}>
                          {this.state.city_complete && (
                            <FormControl
                              className="address_text  add_uppercase"
                              type="text"
                              value={this.state.state}
                              autoComplete="off"
                              style={{
                              display:
                                this.state.check_country !== "CA" &&
                                this.state.country !== "CA" &&
                                this.state.country !== ""
                                  ? "initial"
                                  : "none",
                              fontWeight: 300
                            }}
                              name="province"
                              autoFocus={this.state.city_complete}
                              placeholder="Province"
                              onChange={event =>
                                this.setState({
                                  state: event.target.value,
                                  show_error: false
                                })
                              }
                              onKeyPress={event => {
                                if (event.key === "Enter") {
                                  if (event.target.value) {
                                    if (this.state.state_complete) {
                                      this.handleSubmitAddress();
                                    } else {
                                      this.setState({ state_complete: true });
                                    }
                                  } else {
                                    this.setState({
                                      show_error: true,
                                      error: "Enter Province"
                                    });
                                  }
                                }
                              }}
                            />
                          )}
                        </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={{
                              display:
                                this.state.check_country !== "CA" &&
                                this.state.country !== "CA" &&
                                this.state.country !== ""
                                  ? "initial"
                                  : "none",
                              fontWeight: 300
                            }}
                            autoComplete="off"
                              autoFocus={this.state.state_complete}
                              name="postalcode"
                              onKeyPress={event => {
                                if (event.key === "Enter") {
                                  if (event.target.value) {
                                    this.handleSubmitAddress();
                                  } else {
                                    this.setState({
                                      show_error: true,
                                      error: "Enter Postal Code"
                                    });
                                  }
                                }
                              }}
                              onChange={event =>
                                this.setState({
                                  postalCode: event.target.value,
                                  show_error: false
                                })
                              }
                            />
                          )}
                        </div>
                      </div>
                    </div>
                  </div>
                )}
                {!this.state.loader && (
                  <SelectField
                    hintText="Select Country"
                    // value={value}
                    className="address_text add_uppercase"
                    onChange={this.changeCountry.bind(this)}
                    style={{
                      marginTop: this.state.country !== "" ? this.state.country==="Canada"?"-14px":"-5px" : "30px"
                    }}
                    value={this.state.country}
                    /* buttonStyle={{color: "#fff"}} */
                    iconStyle={{color: "#fff"}}
                    className="userBirthdate_ddm select_countery_ddl sc_textuppercase"
                  >
                    {countries}
                  </SelectField>
                )}
                <div style={{ height: 67, paddingBottom: 10 }}>
                  {this.state.show_error && (
                    <div className="bcd_shownotification_div">
                      <img src={api.image_path+"error-msg-icon.png"} alt="notify img" />
                      <p className="notify_para">{this.state.error}</p>
                      <div className="bcd_shownotification_div1">
                        <a
                          onClick={() => {
                            this.setState({ show_error: false });
                          }}
                          className="notify_para1"
                        >
                          X
                        </a>
                      </div>
                    </div>
                  )}
                </div>
                {!this.state.loader && (
                  <center>
                    
                    {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>
                        )}
                        
                      </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>
    );
  }
}

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 fullMailingAddress;
