import React, { useState } from "react";
import { PayPalScriptProvider, PayPalButtons, FUNDING } from "@paypal/react-paypal-js";
import { Invoice } from '.';

const initialOptions = {
  "client-id": "AQBhJiIcG8lS4K5UoTo_-G5it85lbFpxEcA-WWBb1A-_Nq6YfKUdn05oyg-SgpxzXTyjfpdMceWskq7G",
  currency: "USD",
  intent: "capture"
}
// buyer account: dev01@oemautomation.com, pwd: 3Deerhead
// merchant account: biz01@oemautomation.com, pwd 3Deerhead

const PayPal = ({cart}) => {
  const [showInvoice, setShowInvoice] = useState(false);
  const [invoiceDetails, setInvoiceDetails] = useState({});
  

  const createOrder = (data, actions) => {
    // No idea why "cart" is still empty array... data is showing in the state (React Dev Tools)
    console.log(cart);
    return actions.order.create({
      purchase_units: [{
        description: "Fatek B1-14MR2 PLC",
        amount: {
          currency_code: "USD",
          value: 89.99,
        }
      }]
    });
  }
  
  const onApprove = (data, actions) => {
    return actions.order.capture().then(function(details) {
      setInvoiceDetails(details);
      setShowInvoice(true);
    });
  }

  return (
    <>
      <div className="container">
        <PayPalScriptProvider options={initialOptions}>
          <div style={{ maxWidth: "80px" }}>
            <PayPalButtons
              fundingSource={FUNDING.PAYPAL}
              style={{ height: 25 }}
              forceReRender={[cart]}
              createOrder={createOrder}
              onApprove={onApprove}
            />
          </div>
        </PayPalScriptProvider>
      </div>
      {/* This is a nice touch */}
      {showInvoice && <Invoice invoiceDetails={invoiceDetails} />}
    </>
  );
};

export default PayPal;
