import React from 'react';
import ReactDOM from 'react-dom';

import {NamedError} from './named_error';
import {LoadingDialogReactPages} from './loading_dialog_react_pages';

export function PayPalButton(props) {
  const {paymentMethod, amount, perk, frequency, formData, noPerkCheckbox, fitsAndSizes, perkOption, requiredFields, addError, givingFormError, textFields, priceOtherRef, isValidEmail, validateRequiredFieldsAndDonationAmount, preparePerkData, prepareFieldsData, createBillingAgreement, donateProccessorBaseUrl, successRedirectUrl, setLoading} = props;

  const PayPalButton = paypal.Buttons.driver('react', {React, ReactDOM});

  let recurring = false;
  if (frequency == 'monthly') {
    recurring = true;
  }

  const fieldsData = prepareFieldsData();
  const perkData = preparePerkData();

  const onApprove = async (paypalResponse, actions) => {
    setLoading(true);
    const options = {
      credentials: 'include',
      headers: {
        'Accept': 'application/json, text/html',
        'Content-Type': 'application/json',
      },
      method: 'POST',
      body: JSON.stringify({
        'PayerID': paypalResponse.payerID,
        'amount': amount,
        'fields': fieldsData,
        'paymentMethod': {'name': 'paypal'},
        'perk': perkData,
        'recurring': recurring,
        'token': paypalResponse.orderID,
      }),
    };
    const response = await fetch(`${donateProccessorBaseUrl}/process-paypal`, options);
    const response_data = await response.json();
    if ('errors' in response_data) {
      if (response_data['errors'].length > 0) {
        const errorMessage = response_data['errors'].join("\n");
        addError(new NamedError('paypalError', errorMessage));
        setLoading(false);
        throw new Error(errorMessage);
      } else {
        document.location = successRedirectUrl;
      }
    }
  };

  const onCancel = (data, actions) => {
    setLoading(false);
  };

  if (paymentMethod == 'paypal') {
    return (
      <PayPalButton
        onApprove={onApprove}
        createBillingAgreement={createBillingAgreement}
        onCancel={onCancel}
      />
    );
  }
  return null;
}
