import React from "react";
import api from "./api/api";
import axios from "axios";
import CircularProgress from "@material-ui/core/CircularProgress";
import Script from "react-load-script";
import Drawer from "./drawer";
import Dialog from "material-ui/Dialog";
import FlatButton from "material-ui/FlatButton";
import { isMobile } from "react-device-detect";
import { FormControl } from "react-bootstrap";
import cookie from 'react-cookies';
import SelectField from "material-ui/SelectField";
import MenuItem from "material-ui/MenuItem";
import country from "./country/countries";
let countries = [];
class won1 extends React.Component {
  constructor(props) {
    super(props);
    console.log("session", localStorage.getItem("current_state"));
    console.log("is_active", localStorage.getItem("login_is_active"));
    if (
      localStorage.getItem("current_state") !== "won1" )  {
        this.props.history.push("/menu_page");
      }
    let contest_id = localStorage.getItem("contest_id");
    console.log("contest_id", contest_id);
    let user_id = cookie.load("user_id");
    console.log("user_id", user_id);
    this.state = {
      isOpen: false,
      loader: false,
      user_id: user_id,
      addressLine1: "",
      addressLine2: "",
      check_country: "",
      country:"",
      streetAddress: "",
      countries:"",
      city: "",
      state: "",
      zipcode: "",
      open: false,
      alertmsg: "",
      open: false,
      alertmsg: "",
      edit_address: false,
      addressLine2Enable: false,
      is_active: localStorage.getItem("login_is_active") == 1 ? true : false
    };
    // this.handleUserData = this.handleUserData.bind(this);
    this.handleSend = this.handleSend.bind(this);
    // this.handleSubmit = this.handleSubmit.bind(this);
  }
  componentDidMount() {
    let address = localStorage.getItem("address");
    console.log("address", JSON.parse(address));
    this.setState({
      addressLine1: JSON.parse(address).addressLine1,
      addressLine2: JSON.parse(address).addressLine2,
      city: JSON.parse(address).city,
      state: JSON.parse(address).state,
      zipcode: JSON.parse(address).zipcode,
      country:JSON.parse(address).country
    });
    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("edit_country") === "Canada") {
      this.setState({ check_country: "CA" });
    }
    
  }

  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 });
    }
  };

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

  // handleUserData = () => {
  //   console.log("here");
  //   if (this.state.streetAddress === "") {
  //     this.setState({ open: true, alertmsg: "Enter Street Address" });
  //   } else if (this.state.city === "") {
  //     this.setState({ open: true, alertmsg: "Enter City" });
  //   } else if (this.state.state === "") {
  //     this.setState({ open: true, alertmsg: "Enter Province" });
  //   } else if (this.state.postalCode === "") {
  //     this.setState({ open: true, alertmsg: "Enter Postal Code" });
  //   } else {
  //     this.setState({ loader: true });
  //     console.log("handleUserData");
  //     let self = this;
  //     let editJson = {
  //       action: "update",
  //       user_id: cookie.load("user_id"),

  //       user_metadata: {
  //         shipping_address: {
  //           addressLine1: this.state.addressLine1,
  //           city: this.state.city,
  //           addressLine2: this.state.addressLine2,
  //           state: this.state.state,
  //           zipcode: this.state.zipcode,
  //           country:this.state.country
  //         }
  //       }
  //     };
  //     console.log("editJson", editJson);
  //     axios
  //       .request({
  //         url: api.react_request,
  //         method: "POST",
  //         data: JSON.stringify(editJson)
  //       })
  //       .then(function(response) {
  //         // if (response) {
  //         self.setState({ loader: false });
  //         console.log("response", response);
  //         localStorage.setItem(
  //           "shipping_address",
  //           JSON.stringify(response.data.user_metadata.shipping_address)
  //         );
  //         self.setState({
  //           addressLine1:
  //             response.data.user_metadata.shipping_address.addressLine1,
  //           addressLine2:
  //             response.data.user_metadata.shipping_address.addressLine2,
  //           city: response.data.user_metadata.shipping_address.city,
  //           state: response.data.user_metadata.shipping_address.state,
  //           zipcode: response.data.user_metadata.shipping_address.zipcode,
  //           edit_address: false
  //         });
  //       })
  //       .catch(error => {
  //         console.log("error", error);
  //         self.setState({ loader: false });
  //         self.setState({
  //           open: true,
  //           alertmsg: "Something Wrong... Please try again"
  //         });
  //       });
  //   }
  // };

  handleSend = () => {
    console.log("here");
    if (this.state.addressLine1 === "") {
      this.setState({ open: true, alertmsg: "Enter Street Address" });
    } else if (this.state.city === "") {
      this.setState({ open: true, alertmsg: "Enter City" });
    } else if (this.state.state === "") {
      this.setState({ open: true, alertmsg: "Enter Province" });
    } else if (this.state.postalCode === "") {
      this.setState({ open: true, alertmsg: "Enter Postal Code" });
    } else {
      this.setState({ loader: true });
      console.log("handleSend");
      let self = this;

      let editJson = {
        action: "check_eligible_for_prize",
        user_id: cookie.load("user_id"),
        claim_for: cookie.load("claim_for")
      };
      console.log("editJson", editJson);
      axios
        .request({
          url: api.react_request,
          method: "POST",
          data: JSON.stringify(editJson)
        })
        .then(function(response) {
          // if (response) {
          self.setState({ loader: false });
          console.log("response", response);
          if (response.data.eligible_for_prize===1) {
            if(self.state.edit_address === true){
              let temp_shipping = {};
              temp_shipping.shipping_name = ""
                temp_shipping.addressLine1 = self.state.addressLine1
                temp_shipping.city = self.state.city
                temp_shipping.addressLine2 = self.state.addressLine2
                temp_shipping.state = self.state.state
                temp_shipping.zipcode = self.state.zipcode
                temp_shipping.country = self.state.country
              // shipping.push(temp_shipping)
              console.log("shipping", temp_shipping);
              localStorage.setItem(
                "shipping_address",
                JSON.stringify(temp_shipping)
              );
            }
            
            
            // if (cookie.load("winner_contest_id") === "15") {
            //   cookie.remove("winner_contest_id",{path:'/'});
            //   localStorage.setItem("billing", "billing_address")
            //   localStorage.setItem("current_state", "billing_address")
            //   self.props.history.push("/billing_address");
            // } else {
              localStorage.setItem("current_state", "won2")
              self.props.history.push("/won2");
            // }
          } else {
            self.setState({
              alertmsg: "You are not Eligible",
              open: true
            });
          }
        })
        .catch(error => {
          console.log("error", error);
          self.setState({ loader: false });
          self.setState({
            open: true,
            alertmsg: "Something Wrong... Please try again"
          });
        });
    }
  };

  // handleSubmit = (line1, city2, province2, postalcode2) => {
  //   let finalJson = this.state.finalJson;
  //   // let action = this.props.resetState;
  //   let self = this;
  //   let redirect = this.props.history;
  //   if (this.state.edit_address === true) {
  //     console.log("here");
  //     if (
  //       line1.length == "" ||
  //       city2.length == "" ||
  //       province2.length == "" ||
  //       postalcode2.length == ""
  //     ) {
  //       console.log("here");
  //       this.setState({
  //         open: true,
  //         alertmsg: "Enter Address"
  //       });
  //     } else {
  //       console.log("here");

  //       finalJson = {
  //         action: "check_eligible_for_prize",
  //         user_id: cookie.load("user_id"),
  //         claim_for: cookie.load("claim_for")
  //       };
  //       console.log("finalJson", finalJson);
  //       this.setState({ loader: true });
  //       axios
  //         .request({
  //           url: api.react_request,
  //           method: "POST",
  //           data: JSON.stringify(finalJson)
  //         })
  //         .then(function(response) {
  //           // if (response) {
  //           self.setState({ loader: false });
  //           console.log("response", response);
  //           if (response.data.eligible_for_prize===1) {
  //             localStorage.setItem(
  //               "shipping_address",
  //               JSON.stringify(
  //                 JSON.parse(localStorage.getItem("address"))
  //               )
  //             );
              
  //             if (cookie.load("winner_contest_id") === "15") {
  //               cookie.remove("winner_contest_id");
  //               localStorage.setItem("billing", "billing_address")
  //               localStorage.setItem("current_state", "billing_address")
  //               self.props.history.push("/billing_address");
  //             } else {
  //               localStorage.setItem("current_state", "won2")
  //               self.props.history.push("/won2");
  //             }
  //           } else {
  //             self.setState({
  //               alertmsg: "You are not eligible",
  //               open: true,
  //               edit_address:false
  //             });
  //           }
  //         })
  //         .catch(error => {
  //           console.log("error", error);
  //           self.setState({ loader: false });
  //           self.setState({
  //             open: true,
  //             alertmsg: "Something Wrong... Please try again",
  //             edit_address:false
  //           });
  //         });
  //     }
  //   } else {
  //     finalJson = {
  //       action: "check_eligible_for_prize",
  //       user_id: cookie.load("user_id"),
  //       claim_for: cookie.load("claim_for")
        
  //     };
  //     console.log("finalJson", finalJson);
  //     self.setState({ loader: true });
  //     axios
  //       .request({
  //         url: api.react_request,
  //         method: "POST",
  //         data: JSON.stringify(finalJson)
  //       })
  //       .then(function(response) {
  //         // if (response) {
  //         self.setState({ loader: false });
  //         console.log("response", response);
  //         if (response.data.eligible_for_prize===1) {
  //           localStorage.setItem(
  //             "shipping_address",
  //             JSON.stringify(
  //               JSON.parse(localStorage.getItem("address"))
  //             )
  //           );
            
  //           if (cookie.load("winner_contest_id") === "15") {
  //             cookie.remove("winner_contest_id");
  //             localStorage.setItem("billing", "billing_address")
  //             localStorage.setItem("current_state", "billing_address")
  //             self.props.history.push("/billing_address");
  //           } else {
  //             localStorage.setItem("current_state", "won2")
  //             self.props.history.push("/won2");
  //           }
  //         } else {
  //           self.setState({
  //             alertmsg: "You are not Eligible",
  //             open: true,
  //             edit_address:false
  //           });
  //         }
  //       })
  //       .catch(error => {
  //         console.log("error", error);
  //         self.setState({ loader: false });
  //         self.setState({
  //           open: true,
  //           alertmsg: "Something Wrong... Please try again",
  //           edit_address:false
  //         });
  //       });
  //   }
  // };

  render() {
    // const { open } = this.state;
    // const image_url = api.image_path+"image-2-contest-budget-app.jpg"};
    return (
      <div className="won_first_div">
        <center className="userbirthdatecenter_tag">
          {this.state.is_active && <Drawer prop={this.props} />}
          {this.state.loader && (
            <center>
              <CircularProgress
                size={100}
                style={{ color: "black", marginTop: "17%" }}
              />
            </center>
          )}
          <Dialog
            style={{ textTransform: "capitalize" }}
            actions={
              <FlatButton
                label="OK"
                labelStyle={{ color: "#000" }}
                onClick={() => this.handleClose()}
              />
            }
            modal={false}
            open={this.state.open}
          >
            {this.state.alertmsg}
          </Dialog>
          {!this.state.loader && (
            <div className="won_white_container won1_header_div">
              <div className="won_transparent_div">
                <div className="won_imgtext_div">
                  <p>Congratulations !</p>
                  <p>You've</p>
                  <img src={api.image_path+"won.png"} className="won_imgtext" />
                </div>
              </div>
              <div className="won_inputtext_div">
                <div className="won_inputtext_div_second">
                  <p>Ship my prize to:</p>

                  {/* onClick={()=>{this.state.edit_address?this.handleUserData():this.setState({edit_address:true})}} */}
                  <button
                    onClick={() => {
                      this.state.edit_address
                        ? this.setState({ edit_address: false })
                        : this.setState({ edit_address: true });
                    }}
                    className="btn_SocialShare won_btneditadddress"
                  >
                    {this.state.edit_address ? "Cancel" : "+Edit Address"}
                  </button>
                </div>
                
                  

                <div
                  className="won_inputtext_div_third"
                  
                >
                  {!this.state.edit_address && (
                    <label className="won_address_label">
                      {this.state.addressLine1}
                    </label>
                  )}
                  {this.state.edit_address &&
                    (
                      <div>
                        <input
                          value={this.state.addressLine1}
                          onChange={event => {
                            this.setState({ addressLine1: event.target.value });
                          }}
                          className="won_address_label email_detail"
                          type="text"
                          autoFocus="true"
                          autoComplete="false"
                          onKeyPress={event => {
                            if (event.key === "Enter") {
                              if (event.target.value.length > 0) {
                                this.handleSend();
                              }
                            }
                          }}
                          style={{
                            fontSize: 20,
                            color: "#969696",
                            outline: "none",
                            width: "100%"
                          }}
                          placeholder="Street Address"
                        />
                      </div>
                    )}
                  <br />
                  {this.state.addressLine2 &&
                    !this.state.edit_address && (
                      <div>
                        <label className="won_address_label">
                          {this.state.addressLine2}
                        </label>
                        <br />
                      </div>
                    )}
                  {this.state.edit_address
                     && (
                      <div>
                        <input
                          value={this.state.addressLine2}
                          onChange={event => {
                            this.setState({ addressLine2: event.target.value });
                          }}
                          className="won_address_label email_detail"
                          type="text"
                          autoFocus="true"
                          autoComplete="false"
                          onKeyPress={event => {
                            if (event.key === "Enter") {
                              if (event.target.value.length > 0) {
                                this.handleSend();
                              }
                            }
                          }}
                          style={{
                            fontSize: 20,
                            color: "#969696",
                            outline: "none",
                            width: "100%"
                          }}
                          placeholder="Address Line 2"
                        />
                        <br />
                      </div>
                    )}

                  {!this.state.edit_address && (
                    <label className="won_address_label">
                      {this.state.city}
                      {","}
                      {this.state.state}
                    </label>
                  )}
                  {this.state.edit_address &&
                     (
                      <input
                        value={this.state.city}
                        onChange={event => {
                          this.setState({ city: event.target.value });
                        }}
                        className="won_address_label email_detail"
                        type="text"
                        autoFocus="true"
                        autoComplete="false"
                        onKeyPress={event => {
                          if (event.key === "Enter") {
                            if (event.target.value.length > 0) {
                              this.handleSend();
                            }
                          }
                        }}
                        style={{
                          fontSize: 20,
                          color: "#969696",
                          outline: "none"
                        }}
                        placeholder="City"
                      />
                    )}
                  {this.state.edit_address &&
                     (
                      <input
                        value={this.state.state}
                        onChange={event => {
                          this.setState({ state: event.target.value });
                        }}
                        className="won_address_label email_detail"
                        type="text"
                        autoFocus="true"
                        autoComplete="false"
                        onKeyPress={event => {
                          if (event.key === "Enter") {
                            if (event.target.value.length > 0) {
                              this.handleSend();
                            }
                          }
                        }}
                        style={{
                          fontSize: 20,
                          color: "#969696",
                          outline: "none"
                        }}
                        placeholder="State"
                      />
                    )}
                  <br />
                  {!this.state.edit_address && (
                    <label className="won_address_label">
                      {this.state.zipcode}
                    </label>
                  )}
                  {this.state.edit_address &&
                     (
                      <input
                        value={this.state.zipcode}
                        onChange={event => {
                          this.setState({ zipcode: event.target.value });
                        }}
                        className="won_address_label email_detail"
                        type="text"
                        autoFocus="true"
                        autoComplete="false"
                        onKeyPress={event => {
                          if (event.key === "Enter") {
                            if (event.target.value.length > 0) {
                              this.handleSend();
                            }
                          }
                        }}
                        style={{
                          fontSize: 20,
                          color: "#969696",
                          outline: "none"
                        }}
                        placeholder="Postal Code"
                      />
                    )}
                </div>
                {!this.state.loader && this.state.edit_address &&(
                  <SelectField
                  hintText="Select Country"
                  value={this.state.country}
                  className="address_text add_uppercase"
                  onChange={this.changeCountry.bind(this)}
                  style={styles.ddm}
                  value={this.state.country}
                  className="userBirthdate_ddm select_countery_ddl select_countery_wonddl"
                >
                  {countries}
                </SelectField>
                  )}
              </div>
              <div className="user_birthdate won_div won_div1">
                <button
                  onClick={event => {
                    this.handleSend();
                  }}
                  className="btn_SocialShare won_btnsend"
                >
                  Send it!
                </button>
                <p className="won_notepara">
                  Please note: if after seven(7) days, the prize remains
                  unclaimed, family.one reserves the right to either select a
                  new winner or cancel the prize.
                </p>
                <a
                  onClick={() => {
                    localStorage.setItem("current_state", "menu_page")
                    this.props.history.push("/menu_page");
                  }}
                  className="won_anchortag"
                >
                  Skip for now
                </a>
              </div>
            </div>
          )}
        </center>
      </div>
    );
  }
}
const styles = {
  labelStyle: {
    color: "rgba(224, 214, 214, 0.87)",
    fontSize: 14
  },
  
};

export default won1;
