import React, { useContext, useEffect, useState } from 'react';
import { PayPalButtons, usePayPalScriptReducer } from '@paypal/react-paypal-js';
import { useRouter } from 'next/router';
import { CartContext } from 'src/contexts/cart';
import SaveOrder from 'src/api/saveOrder';
import GetOrderDetails from 'src/api/getOrderDetails';
import CancelOrder from 'src/api/cancelOrder';

const Checkout = () => {
  const router = useRouter();
  const { cart, total_price, products, proceedCheckOutCart, emptyCart } = useContext(CartContext);
  const [{ options, isPending }, dispatch] = usePayPalScriptReducer();
  const currency_code = 'HKD';
  const [custom_id, setCustomId] = useState('');
  const share = {};

  const onCreateOrder = async (data, actions) => {
    const proceed = async () => {
      try {
        let { order_details } = await GetOrderDetails({ cart, currency_code });

        share['custom_id'] = order_details['custom_id'];
        return actions.order.create({ purchase_units: [{ amount: { value: total_price } }] });
      } catch (error) {
        console.error(error);
      }
    };
    return await proceed();
  };

  const onCancelOrder = async (data, actions) => {
    const cancel = async () => {
      try {
        await CancelOrder({ custom_id: share['custom_id'] });
        alert('Your order has been cancelled');
      } catch (error) {
        console.error(error);
      }
    };
    return await cancel();
  };

  const onApproveOrder = (data, actions) => {
    return actions.order
      .capture()
      .then(async details => {
        let { custom_id } = share;
        await SaveOrder({ custom_id });
        return await emptyCart();
      })
      .then(() => {
        (async () => {
          await proceedCheckOutCart();
          router.replace('/shopfront/cart/Thankyou');
        })();
      })
      .catch(err => console.error(err));
  };

  return (
    <div className="checkout">
      {isPending ? (
        <p>LOADING...</p>
      ) : (
        <>
          <PayPalButtons
            style={{ layout: 'vertical' }}
            createOrder={(data, actions) => onCreateOrder(data, actions)}
            onApprove={(data, actions) => onApproveOrder(data, actions)}
            onCancel={(data, actions) => onCancelOrder(data, actions)}
          />
        </>
      )}
    </div>
  );
};

export default Checkout;
