import React, { Component } from "react";
import { CardElement, injectStripe } from "react-stripe-elements";
import axios from "axios";
import CircularProgress from "@material-ui/core/CircularProgress";
import api from "./api/api";
import cookie from "react-cookies";
var base64 = require("base-64");

let user_encrypt_id = base64.encode(cookie.load("user_id"));
class CheckoutForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loader: false
    };
    console.log("props", this.props);
    this.submit = this.submit.bind(this);
  }
  async submit(ev) {
    this.setState({ loader: true });
    console.log("ev", this.props);
    let billing_address = JSON.parse( localStorage.getItem("billing_address"))
    console.log("adrrss",JSON.parse( localStorage.getItem("billing_address")))
    let { token } = await this.props.stripe.createToken({
      name:localStorage.getItem("first_name")+" "+localStorage.getItem("last_name"),
      address_line1: billing_address.addressLine1,
      address_line2: billing_address.addressLine2,
      address_city: billing_address.city,
      address_state: billing_address.state,
      address_zip: billing_address.zipcode,
      address_country: billing_address.country,
      metadata: {'product_name':localStorage.getItem("product_name")}
    });
    console.log("token", token);
    if (token) {
      let finalJson = {
        action: "make_payment",
        stripeToken: token.id,
        user_id: this.props.prop.user_id,
        product_id: this.props.prop.product_id,
        upgraded: this.props.prop.upgraded,
        product_name: this.props.prop.product_name,
        product_price: this.props.prop.product_price,
        shipping_price: this.props.prop.shipping_price,
        shipping_address:localStorage.getItem("shipping_address"),
        billing_address:localStorage.getItem("billing_address"),
        tax: this.props.prop.tax,
        claim_for: cookie.load("claim_for"),
        refund_flag:0
      };
      var self = this;
      console.log("finalJson", finalJson);
      axios
        .request({
          url: api.payment_stripe,
          method: "POST",
          data: JSON.stringify(finalJson)
        })
        .then(function(response) {
          console.log("response", response);
          console.log("this", self);
          self.setState({ loader: false });
          if (response.data.payment_status === "successful") {
            localStorage.setItem("current_state", "payment_successfull");
            localStorage.removeItem("shipping_address")
            cookie.remove("claim_for",{path:'/'})
            self.props.push.push("/payment_successfull");
          } else {
            localStorage.setItem("current_state", "payment_failed");
            self.props.push.push("/payment_failed");
          }
        })
        .catch(error=>{
          console.log("error",error)
          self.setState({ loader: false });
          self.setState({
            open: true,
            alertmsg: "Something Wrong... Please try again later"
          });
        })
    } else {
      console.log("this", self);
      this.setState({ loader: false });
    }
  }

  render() {
    return (
      <div>
        <div className="checkout">
          <p>Credit Card Information</p>
        </div>
        <CardElement hidePostalCode={true}/>
        <br />

        <div className="product_info">
          <p>Product name: {this.props.prop.product_name}</p>
          <p>Product Price: ${this.props.prop.product_price}</p>
          <p>Shipping Price: ${this.props.prop.shipping_price}</p>
          <p>Tax: ${this.props.prop.tax}</p>
          <p>Total Price: ${this.props.prop.total_price}</p>
        </div>
        <div className="product_orientation_orderbtn_div">
          {this.state.loader && (
            <center>
              <CircularProgress
                size={36}
                style={{ color: "black", marginTop: "17%" }}
              />
            </center>
          )}
          {!this.state.loader && (
            <button className="btnorder" onClick={this.submit}>
              Pay{" $" + this.props.prop.total_price}
            </button>
          )}
        </div>
      </div>
    );
  }
}

export default injectStripe(CheckoutForm);
