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 { Elements, StripeProvider } from "react-stripe-elements";
import CheckoutForm from "./CheckoutForm";
import cookie from "react-cookies";
var base64 = require("base-64");

class paymentStripe extends Component {
  constructor(props) {
    super(props);
    if (
      localStorage.getItem("current_state") !== "payment_stripe" ||
      cookie.load("user_id") == "" ||
      cookie.load("user_id") == "undefined" ||
      typeof cookie.load("user_id") == undefined
    ) {
      this.props.history.push("/");
    }
    console.log("session", localStorage.getItem("current_state"));
    console.log("is_active", localStorage.getItem("login_is_active"));
    console.log("user_id", cookie.load("user_id"));
    let user_encrypt_id = base64.encode(cookie.load("user_id"));
    console.log("user_encrypt_id", user_encrypt_id);
    // 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,
      product_name: localStorage.getItem("product_name"),
      product_price: localStorage.getItem("product_price"),
      shipping_price: localStorage.getItem("shipping_price"),
      product_id: localStorage.getItem("product_id"),
      total_price: localStorage.getItem("total_price"),
      upgraded_price: localStorage.getItem("upgraded_price"),
      upgraded: localStorage.getItem("upgraded"),
      tax: localStorage.getItem("tax"),
      user_id: user_encrypt_id,
      card: [],
      is_card: false,
      card_id: "",
      customer_id: "",
      stripe_public_key:""
    };
    console.log("this", this.props);
    this.handleClose.bind(this);
    this.handleRadio.bind(this);
    this.handlePay.bind(this);
  }
  handleClose = () => {
    this.setState({ open: false });
  };

  handleRadio = cardlist => {
    console.log("here", cardlist);
    this.setState({
      card_id: cardlist.card_id,
      customer_id: cardlist.customer_id
    });
  };

  handlePay = () => {
    console.log("here", this.state.card_id);
    console.log("here", this.state.customer_id);
    if (this.state.card_id === "" || this.state.customer_id === "") {
      console.log("hi");
    } else {
      let finalJson = {
        action: "make_payment",
        card_id: this.state.card_id,
        claim_for: cookie.load("claim_for"),
        customer_id: this.state.customer_id,
        user_id: this.state.user_id,
        product_id: localStorage.getItem("product_id"),
        upgraded: localStorage.getItem("upgraded"),
        product_name: localStorage.getItem("product_name"),
        product_price: localStorage.getItem("product_price"),
        shipping_price: localStorage.getItem("shipping_price"),
        total_price: localStorage.getItem("total_price"),
        shipping_address: localStorage.getItem("shipping_address"),
        billing_address: localStorage.getItem("billing_address"),
        upgraded_price: localStorage.getItem("upgraded_price"),
        tax: localStorage.getItem("tax"),
        shipping_address: localStorage.getItem("shipping_address"),
        refund_flag:0
      };
      var self = this;
      self.setState({ loader: true });
      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);
          if (response.data.payment_status === "successful") {
            self.setState({ loader: false });
            localStorage.removeItem("shipping_address")
            cookie.remove("claim_for",{path:'/'})
            self.props.history.push("/payment_successfull");
          } else {
            self.setState({ loader: false });
            localStorage.setItem("current_state", "payment_failed"),
              self.props.history.push("/payment_failed");
          }
        })
        .catch(error => {
          console.log("error", error);
          self.setState({ loader: false });
          self.setState({
            show_error: true,
            error: "Something Wrong... Please try Again"
          });
        });
    }
  };

  componentDidMount = () => {
    var self = this;
    let get_information = {
      action: "get_information",
      stripe_key:1,
      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) {
          self.setState({ loader: false,stripe_public_key:response.data.stripe_public_key });
          if (
            response.data.user_metadata.payment_data &&
            response.data.user_metadata.payment_data.length > 0
          ) {
            self.setState({
              card: response.data.user_metadata.payment_data,
              is_card: true
            });
            response.data.user_metadata.payment_data.forEach(element => {
              self.setState({
                card_id: element.card_id,
                customer_id: element.customer_id
              });
            });
          }
          console.log("response", response.data.user_metadata.payment_data);
        }
      })
      .catch(error => {
        console.log("error", error);
        self.setState({ loader: false });
        self.setState({
          open: true,
          alertmsg: "Something Wrong... Please try again"
        });
      });
  };

  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 &&
            this.state.pay && (
              <div className="inner_container2 product_orientation1_container m_t10 checkout_div">
                <div className="white_container">
                  {!this.state.is_card && this.state.stripe_public_key !=="" &&(
                    
                    <StripeProvider
                    
                      apiKey={this.state.stripe_public_key}
                      //apiKey="pk_test_Irmc3PqgnonQqTbmyuN3TGrz"
                      className="external_checkout"
                    >
                    
                      <div className="example">
                      {console.log(this.state.stripe_public_key)}
                        <Elements>
                          <CheckoutForm
                            className="external_checkout"
                            prop={this.state}
                            push={this.props.history}
                          />
                        </Elements>
                      </div>
                    </StripeProvider>
                  )}
                  {this.state.is_card &&
                    this.state.card.length > 0 &&
                    this.state.card.map((cardList, indexs) => (
                      <div key={indexs}>
                        <input
                          onClick={() => {
                            this.handleRadio(cardList);
                          }}
                          type="radio"
                          name="pay"
                          value={cardList.card_id}
                          defaultChecked
                        />&nbsp;
                        <div style={{ marginLeft: 25, marginTop: -18 }}>
                          <label>{cardList.brand}</label>
                          <br />

                          <label>
                            {"**** **** **** "}
                            {cardList.last4}
                          </label>
                          <br />
                          <label>
                            Expires {cardList.exp_month}
                            {"/"}
                            {cardList.exp_year}
                          </label>
                          <br />
                          <br />
                        </div>
                      </div>
                    ))}
                  {this.state.is_card && (
                    <div className="card_list">
                      <p>Product name: {this.state.product_name}</p>
                      <p>Product Price: ${this.state.product_price}</p>
                      <p>Shipping Price: ${this.state.shipping_price}</p>
                      <p>Tax: ${this.state.tax}</p>
                      <p>Total Price: ${this.state.total_price}</p>
                      <button onClick={() => this.handlePay()}>
                        Pay{" $" + this.state.total_price}
                      </button>
                      <button onClick={() => this.setState({ is_card: false })}>
                        Pay with another Card
                      </button>
                    </div>
                  )}
                  <div />
                </div>
              </div>
            )}
        </div>
      </div>
    );
  }
}
export default paymentStripe;
