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) => {
    return actions.order.create({
      purchase_units: cart.map(item => {
        return {
          reference_id: item.ID,
          description: item.productName,
          amount: {
            currency_code: "USD",
            value: item.price, // using price rather than discounted price for now, (item ID 2 has discounted price: "0.00")
          }
        };
      })
    });
  }
  
  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]}
              disabled={cart.length === 0}
              createOrder={createOrder}
              onApprove={onApprove}
            />
          </div>
        </PayPalScriptProvider>
      </div>
      {showInvoice && <Invoice invoiceDetails={invoiceDetails} />}
    </>
  );
};

export default PayPal;
