import React, { Component } from "react";
import Drawer from "./drawer";

import axios from "axios";
import CircularProgress from "@material-ui/core/CircularProgress";
import FlatButton from "material-ui/FlatButton";
import Dialog from "material-ui/Dialog";
import api from "./api/api";
import cookie from "react-cookies";
import Checkbox from "material-ui/Checkbox";
import SelectField from "material-ui/SelectField";
import MenuItem from "material-ui/MenuItem";
import country from "./country/countries";
let countries = [];
class billingAddress extends Component {
  constructor(props) {
    super(props);
    if (
    localStorage.getItem("current_state") !== "billing_address" )  {
      this.props.history.push("/menu_page");
    }
    console.log("session", localStorage.getItem("current_state"));
    console.log("is_active", localStorage.getItem("login_is_active"));
    // console.log("this",this._reactInternalFiber.memoizedProps.location.state)
    this.state = {
      loader: false,
      is_active: localStorage.getItem("login_is_active") == 1 ? true : false,
      open: false,
      alertmsg: "",
      pay: true,
      name: "",
      email: "",
      shipping_state:"",
      shipping_addressLine1: "",
      shipping_addressLine2: "",
      shipping_city: "",
      shipping_postalCode: "",
      addressLine1: "",
      addressLine2: "",
      city: "",
      postalCode: "",
      card: [],
      is_card: false,
      card_id: "",
      customer_id: "",
      checked: false,
      country: "",
      country1: "",
      error: "",
      shipping_name: ""
    };
    console.log("this", this.props);
    this.handleClose.bind(this);
    this.handleSubmitAddress.bind(this);
    this.changeCountry.bind(this);
  }
  handleClose = () => {
    this.setState({ open: false });
  };

  handleSubmitAddress = () => {
    let finalJson = this.state.finalJson;
    let cname = [];
    let redirect = this.props.history;
    console.log("name", this.state.name);
    cname = this.state.name.split(" ");

    let first_name = cname[0];
    let last_name = cname[1];
    console.log("first_name", first_name);
    console.log("last_name", last_name);
    let address_check = 0;
    if (
      this.state.state &&
      this.state.postalCode &&
      this.state.city &&
      this.state.addressLine1
    ) {
      if (this.state.checked) {
        if (
          this.state.shipping_name &&
          this.state.shipping_state &&
          this.state.shipping_postalCode &&
          this.state.shipping_city &&
          this.state.shipping_addressLine1
        ) {
          var self = this;
          finalJson = {
            action: "update",

            user_id: cookie.load("user_id"),
            user_metadata: {
              is_active: 1,
              first_name:
                first_name.charAt(0).toUpperCase() + first_name.substr(1),
              last_name:
                last_name.charAt(0).toUpperCase() + last_name.substr(1),
              billing_address: {
                addressLine1: this.state.addressLine1,
                city: this.state.city,
                addressLine2: this.state.addressLine2,
                state: this.state.state,
                zipcode: this.state.postalCode,
                country: this.state.country1
              }
            }
          };
          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);
              let temp_shipping = {};
              (temp_shipping.shipping_name = self.state.checked
                ? self.state.shipping_name
                : self.state.name),
                (temp_shipping.addressLine1 = self.state.checked
                  ? self.state.shipping_addressLine1
                  : self.state.addressLine1),
                (temp_shipping.city = self.state.checked
                  ? self.state.shipping_city
                  : self.state.city),
                (temp_shipping.addressLine2 = self.state.checked
                  ? self.state.shipping_addressLine2
                  : self.state.addressLine2),
                (temp_shipping.state = self.state.checked
                  ? self.state.shipping_state
                  : self.state.state),
                (temp_shipping.zipcode = self.state.checked
                  ? self.state.shipping_postalCode
                  : self.state.postalCode),
                (temp_shipping.country = self.state.checked
                  ? self.state.country
                  : self.state.country1);
              // shipping.push(temp_shipping)
              console.log("shipping", temp_shipping);
              localStorage.setItem(
                "shipping_address",
                JSON.stringify(temp_shipping)
              );
              localStorage.setItem(
                "first_name",
                response.data.user_metadata.first_name
              );
              localStorage.setItem(
                "last_name",
                response.data.user_metadata.last_name
              );
              localStorage.setItem(
                "billing_address",
                JSON.stringify(response.data.user_metadata.billing_address)
              );
              self.setState({ loader: false });

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

              // }
            })
            .catch(error => {
              console.log("error", error);
              self.setState({ loader: false });
              self.setState({
                show_error: true,
                error: "Something Wrong... Please try again later"
              });
            });
        } else {
          console.log("not ok");
          if (this.state.shipping_name === "") {
            this.setState({ show_error: true, error: "Enter Name" });
          } else if (this.state.shipping_addressLine1 === "") {
            this.setState({ show_error: true, error: "Enter Address Line1" });
          } else if (this.state.shipping_city === "") {
            this.setState({ show_error: true, error: "Enter City" });
          } else if (this.state.shipping_state === "") {
            this.setState({ show_error: true, error: "Enter Province" });
          } else if (this.state.shipping_postalCode === "") {
            this.setState({ show_error: true, error: "Enter Postal Code" });
          }
        }
      } else {
        var self = this;
        finalJson = {
          action: "update",

          user_id: cookie.load("user_id"),
          user_metadata: {
            is_active: 1,
            first_name:
              first_name.charAt(0).toUpperCase() + first_name.substr(1),
            last_name: last_name.charAt(0).toUpperCase() + last_name.substr(1),
            billing_address: {
              addressLine1: this.state.addressLine1,
              city: this.state.city,
              addressLine2: this.state.addressLine2,
              state: this.state.state,
              zipcode: this.state.postalCode,
              country: this.state.country1
            }
          }
        };
        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);
            let temp_shipping = {};
            (temp_shipping.shipping_name = self.state.checked
              ? self.state.shipping_name
              : self.state.name),
              (temp_shipping.addressLine1 = self.state.checked
                ? self.state.shipping_addressLine1
                : self.state.addressLine1),
              (temp_shipping.city = self.state.checked
                ? self.state.shipping_city
                : self.state.city),
              (temp_shipping.addressLine2 = self.state.checked
                ? self.state.shipping_addressLine2
                : self.state.addressLine2),
              (temp_shipping.state = self.state.checked
                ? self.state.shipping_state
                : self.state.state),
              (temp_shipping.zipcode = self.state.checked
                ? self.state.shipping_postalCode
                : self.state.postalCode),
              (temp_shipping.country = self.state.checked
                ? self.state.country
                : self.state.country1);
            // shipping.push(temp_shipping)
            console.log("shipping", temp_shipping);
            localStorage.setItem(
              "shipping_address",
              JSON.stringify(temp_shipping)
            );
            localStorage.setItem(
              "first_name",
              response.data.user_metadata.first_name
            );
            localStorage.setItem(
              "last_name",
              response.data.user_metadata.last_name
            );
            localStorage.setItem(
              "billing_address",
              JSON.stringify(response.data.user_metadata.billing_address)
            );
            self.setState({ loader: false });

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

            // }
          })
          .catch(error => {
            console.log("error", error);
            self.setState({ loader: false });
            self.setState({
              show_error: true,
              error: "Something Wrong... Please try again later"
            });
          });
      }
    } else {
      console.log("not ok");
      if (this.state.addressLine1 === "") {
        this.setState({ show_error: true, error: "Enter Address Line1" });
      } 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" });
      }
    }
  };
  changeCountry1 = (event, index, value) => {
    let country_code;
    console.log("value", value);
    this.setState({ country1: value });
    // if (value === "Canada") {
    //   country_code = "CA";
    //   this.setState({ check_country: country_code });
    // }
    // else{
    //   country_code = "value";
    //   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 });
    // }
  };
  componentDidMount = () => {
    var self = this;
    let get_information = {
      action: "get_information",
      user_id: cookie.load("user_id")
    };
    console.log("get_information", get_information);
    self.setState({ loader: true });
    axios
      .request({
        method: "POST",
        url: api.react_request,
        data: JSON.stringify(get_information)
      })
      .then(function(response) {
        console.log("response", response);
        if (response) {
          // console.log(JSON.parse(localStorage.getItem("shipping_address")))
          // if (typeof localStorage.getItem("shipping_address") !== undefined &&
          // localStorage.getItem("shipping_address") !== "undefined" &&
          // localStorage.getItem("shipping_address") !== "null" &&
          // localStorage.getItem("shipping_address") !== null &&
          // localStorage.getItem("shipping_address") ) {
          //   let shipping_address = JSON.parse(localStorage.getItem("shipping_address"))
          // self.setState({
          //   shipping_name:shipping_address.shipping_name,
          //   shipping_addressLine1:
          //   shipping_address.addressLine1,
          //   shipping_addressLine2:
          //   shipping_address.addressLine2,
          //   shipping_city: shipping_address.city,
          //   shipping_state:
          //   shipping_address.state,
          //   shipping_postalCode:
          //   shipping_address.zipcode,
          //     country:shipping_address.country,
          //   checked: true
          // });
          // }
          self.setState({
            name:
              response.data.user_metadata.first_name +
              " " +
              response.data.user_metadata.last_name,
            email: response.data.email
          });
          if (response.data.user_metadata.billing_address) {
            self.setState({
              addressLine1:
                response.data.user_metadata.billing_address.addressLine1,
              addressLine2:
                response.data.user_metadata.billing_address.addressLine2,
              city: response.data.user_metadata.billing_address.city,
              state: response.data.user_metadata.billing_address.state,
              postalCode: response.data.user_metadata.billing_address.zipcode,
              country1: response.data.user_metadata.billing_address.country
            });
          } else {
            self.setState({
              addressLine1: response.data.user_metadata.address.addressLine1,
              addressLine2: response.data.user_metadata.address.addressLine2,
              city: response.data.user_metadata.address.city,
              state: response.data.user_metadata.address.state,
              postalCode: response.data.user_metadata.address.zipcode,
              country1: response.data.user_metadata.address.country
            });
          }

          self.setState({ loader: false });
        }
      })
      .catch(error => {
        console.log("error", error);
        self.setState({ loader: false });
        self.setState({ open: true, alertmsg: "Something Wrong" });
      });
    var country_arr = country;

    for (let i = 0; i < country_arr.length; i++) {
      countries.push(
        <MenuItem
          value={country_arr[i]}
          key={i}
          primaryText={country_arr[i]}
          style={{
            top: "auto",
            bottom: "100%"
          }}
        />
      );
    }
  };

  updateCheck() {
    this.setState(oldState => {
      return {
        checked: !oldState.checked
      };
    });
  }

  render() {
    return (
      <div className="page-bg">
        <center>
          {this.state.loader && (
            <div>
              <CircularProgress
                size={100}
                style={{ color: "black", marginTop: "17%" }}
              />
            </div>
          )}
          {this.state.is_active && <Drawer prop={this.props} />}
        </center>
        {/* {this.state.is_active && <Drawer prop={this.props} />} */}
        {!this.state.loader && (
          <div className="welcome_img m_t10 text-center">
            <img
              src={api.image_path + "familyone_logo.png"}
              alt=""
              title=""
              className="product_orientation_images"
            />
          </div>
        )}
        <div className="inner_container2 product_orientation1_container m_t10 ">
          <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 className="inner_container2 product_orientation1_container m_t10 checkout_div">
              <div className="white_container">
                <p className="sp_para">BILLING INFORMATION</p>
                <div>
                  <div className="sb_formdiv">
                    <label>
                      <span>Name</span>
                      <input
                        type="text"
                        autoComplete="off"
                        className="sb_txtName sb_txt"
                        placeholder="Enter Your Name"
                        value={this.state.name}
                        onChange={event => {
                          this.setState({ name: event.target.value });
                        }}
                        onKeyPress={event => {
                          if (event.key === "Enter") {
                            if (event.target.value.length > 0) {
                              this.handleSubmitAddress();
                            } else {
                              this.setState({
                                show_error: true,
                                error: "Enter Your Name"
                              });
                            }
                          }
                        }}
                      />
                    </label>
                    <label>
                      <span>Email</span>
                      <input
                        type="text"
                        autoComplete="off"
                        className="sb_txtmail sb_txt"
                        placeholder="Enter Your Email"
                        value={this.state.email}
                        onChange={event => {
                          this.setState({ email: event.target.value });
                        }}
                        onKeyPress={event => {
                          if (event.key === "Enter") {
                            if (event.target.value.length > 0) {
                              this.handleSubmitAddress();
                            } else {
                              this.setState({
                                show_error: true,
                                error: "Enter Your Email"
                              });
                            }
                          }
                        }}
                      />
                    </label>
                    <label>
                      <span>Address</span>
                      <input
                        type="text"
                        autoComplete="off"
                        className="sb_txtAddress sb_txt"
                        placeholder="Enter Your Address"
                        value={this.state.addressLine1}
                        onChange={event => {
                          this.setState({ addressLine1: event.target.value });
                        }}
                        onKeyPress={event => {
                          if (event.key === "Enter") {
                            if (event.target.value.length > 0) {
                              this.handleSubmitAddress();
                            } else {
                              this.setState({
                                show_error: true,
                                error: "Enter Your Address"
                              });
                            }
                          }
                        }}
                      />
                    </label>
                    <label>
                      <span>City</span>
                      <input
                        type="text"
                        autoComplete="off"
                        className="sb_txtcity sb_txt"
                        placeholder="Enter Your City"
                        value={this.state.city}
                        onChange={event => {
                          this.setState({ city: event.target.value });
                        }}
                        onKeyPress={event => {
                          if (event.key === "Enter") {
                            if (event.target.value.length > 0) {
                              this.handleSubmitAddress();
                            } else {
                              this.setState({
                                show_error: true,
                                error: "Enter Your City"
                              });
                            }
                          }
                        }}
                      />
                    </label>
                    <label>
                      <span>Province</span>
                      <input
                        type="text"
                        autoComplete="off"
                        className="sb_txtpostalcode sb_txt"
                        placeholder="Enter Your Province"
                        value={this.state.state}
                        onChange={event => {
                          this.setState({ state: event.target.value });
                        }}
                        onKeyPress={event => {
                          if (event.key === "Enter") {
                            if (event.target.value.length > 0) {
                              this.handleSubmitAddress();
                            } else {
                              this.setState({
                                show_error: true,
                                error: "Enter Your Province"
                              });
                            }
                          }
                        }}
                      />
                    </label>
                    <label>
                      <span>Postal Code</span>
                      <input
                        type="text"
                        autoComplete="off"
                        className="sb_txtpostalcode sb_txt"
                        placeholder="Enter Your Postal Code"
                        value={this.state.postalCode}
                        onChange={event => {
                          this.setState({ postalCode: event.target.value });
                        }}
                        onKeyPress={event => {
                          if (event.key === "Enter") {
                            if (event.target.value.length > 0) {
                              this.handleSubmitAddress();
                            } else {
                              this.setState({
                                show_error: true,
                                error: "Enter Postal Code"
                              });
                            }
                          }
                        }}
                      />
                    </label>
                    <label>
                      <span>Country</span>
                      <SelectField
                        hintText="Select Country"
                        // value={value}
                        autoComplete="off"
                        className="address_text add_uppercase"
                        onChange={this.changeCountry1.bind(this)}
                        value={this.state.country1}
                        className="userBirthdate_ddm country_shipbillingaddress"
                      >
                        {countries}
                      </SelectField>
                    </label>
                    <Checkbox
                      label="SHIP TO A DIFFERENT ADDRESS?"
                      labelStyle={{ width: "calc(100% - 140px)" }}
                      checked={this.state.checked}
                      onCheck={this.updateCheck.bind(this)}
                      style={styles.checkbox}
                      className="shopbilling_infocheckbox"
                    />
                    {this.state.checked && (
                      <div>
                        <p className="sp_para">SHIPPING INFORMATION</p>
                        <label>
                          <span>Name</span>
                          <input
                            type="text"
                            className="sb_txtName sb_txt"
                            placeholder="Enter Name"
                            autoComplete="off"
                            value={this.state.shipping_name}
                            onChange={event => {
                              this.setState({
                                shipping_name: event.target.value
                              });
                            }}
                            onKeyPress={event => {
                              if (event.key === "Enter") {
                                if (event.target.value.length > 0) {
                                  this.handleSubmitAddress();
                                } else {
                                  this.setState({
                                    show_error: true,
                                    error: "Enter Your Name"
                                  });
                                }
                              }
                            }}
                          />
                        </label>
                        <label>
                          <span>Address</span>
                          <input
                            type="text"
                            className="sb_txtAddress sb_txt"
                            placeholder="Enter Your Address"
                            value={this.state.shipping_addressLine1}
                            onChange={event => {
                              this.setState({
                                shipping_addressLine1: event.target.value
                              });
                            }}
                            autoComplete="off"
                            onKeyPress={event => {
                              if (event.key === "Enter") {
                                if (event.target.value.length > 0) {
                                  this.handleSubmitAddress();
                                } else {
                                  this.setState({
                                    show_error: true,
                                    error: "Enter Your Address Line 1"
                                  });
                                }
                              }
                            }}
                          />
                        </label>
                        <label>
                          <span>City</span>
                          <input
                            autoComplete="off"
                            type="text"
                            className="sb_txtcity sb_txt"
                            placeholder="Enter Your City"
                            value={this.state.shipping_city}
                            onChange={event => {
                              this.setState({
                                shipping_city: event.target.value
                              });
                            }}
                            onKeyPress={event => {
                              if (event.key === "Enter") {
                                if (event.target.value.length > 0) {
                                  this.handleSubmitAddress();
                                } else {
                                  this.setState({
                                    show_error: true,
                                    error: "Enter Your City"
                                  });
                                }
                              }
                            }}
                          />
                        </label>
                        <label>
                          <span>Province</span>
                          <input
                            autoComplete="off"
                            type="text"
                            className="sb_txtpostalcode sb_txt"
                            placeholder="Enter Your Province"
                            value={this.state.shipping_state}
                            onChange={event => {
                              this.setState({
                                shipping_state: event.target.value
                              });
                            }}
                            onKeyPress={event => {
                              if (event.key === "Enter") {
                                if (event.target.value.length > 0) {
                                  this.handleSubmitAddress();
                                } else {
                                  this.setState({
                                    show_error: true,
                                    error: "Enter Your Province"
                                  });
                                }
                              }
                            }}
                          />
                        </label>
                        <label>
                          <span>Postal Code</span>
                          <input
                            autoComplete="off"
                            type="text"
                            className="sb_txtpostalcode sb_txt"
                            placeholder="Enter Your Postal Code"
                            value={this.state.shipping_postalCode}
                            onChange={event => {
                              this.setState({
                                shipping_postalCode: event.target.value
                              });
                            }}
                            onKeyPress={event => {
                              if (event.key === "Enter") {
                                if (event.target.value.length > 0) {
                                  this.handleSubmitAddress();
                                } else {
                                  this.setState({
                                    show_error: true,
                                    error: "Enter Your Postal Code"
                                  });
                                }
                              }
                            }}
                          />
                        </label>
                        <label>
                          <span>Country</span>
                          <SelectField
                            hintText="Select Country"
                            // value={value}
                            className="address_text add_uppercase"
                            onChange={this.changeCountry.bind(this)}
                            value={this.state.country}
                            className="userBirthdate_ddm country_shipbillingaddress"
                          >
                            {countries}
                          </SelectField>
                        </label>
                      </div>
                    )}
                    <div />
                    <div className="product_orientation_orderbtn_div">
                      <button
                        onClick={() => {
                          this.handleSubmitAddress();
                        }}
                        className="btnorder"
                      >
                        Next
                      </button>
                    </div>
                  </div>
                </div>
              </div>
              <div className="fac_btn_arrrow">
                <div className="fac_btn_prev_div">
                  <img
                    src={api.image_path + "prev_arrow_one.jpg"}
                    width="40"
                    className="next_icon next_left"
                    onClick={() => {
                      {
                        localStorage.setItem(
                          "current_state",
                          "product_orientation"
                        );
                        this.props.history.push("/product_orientation");
                      }
                    }}
                  />
                </div>
                <div className="fac_btn_next_div">
                  <img
                    src={api.image_path + "next_arrow_one.png"}
                    width="40"
                    className="next_icon next_right"
                    onClick={() => {
                      this.handleSubmitAddress();
                    }}
                  />
                </div>
              </div>
              <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>
            </div>
          )}
        </div>
      </div>
    );
  }
}

const styles = {
  block: {
    maxWidth: 250
  },
  checkbox: {
    marginBottom: 16
  }
};

export default billingAddress;
