import React, {useEffect} from 'react';
import {injectStripe} from 'react-stripe-elements';
import {StripeCreditCardForm} from './stripe_credit_card_form';
import {NamedError} from './named_error';

function _StripeProcessor(props) {
  const {stripe, formState, setErrors, fieldsData, perkData, tokenData, frequency, donateProccessorBaseUrl, setLoading, successRedirectUrl, paymentMethod, onStripeFieldChange, errors, selectedPrice} = props;

  useEffect(() => {
    if (formState != 'submitted') {
      return;
    }
    async function createTokenAndSubmitPayment() {
      let newErrors = [];
      const tokenCreated = await stripe.createToken(tokenData);
      if ('token' in tokenCreated) {
        const token = tokenCreated.token.id;
        let recurring = false;
        if (frequency == 'monthly') {
          recurring = true;
        }
        const options = {
          headers: {
            'Content-Type': 'application/json; charset=UTF-8',
            'Accept': 'application/json, text/html',
          },
          method: 'POST',
          body: JSON.stringify({
            'token': token,
            'amount': selectedPrice,
            'fields': fieldsData,
            'paymentMethod': {'name': 'credit_card'},
            'perk': perkData,
            'recurring': recurring,
          }),
          credentials: 'include',
        };
        const result = await fetch(donateProccessorBaseUrl + '/process-stripe', options);
        const data = await result.json();
        if (data['errors'].length > 0) {
          var errorMsgs = new Array();
          data['errors'].forEach(function(error) {
            errorMsgs.push(error);
          });
          const errorMessage = errorMsgs.join('\n');
          setLoading(false);
          newErrors.push(new NamedError('stripeError', errorMessage));
        } else {
          window.location.href = successRedirectUrl;
        }
      } else if ('error' in tokenCreated) {
        const errorMessage = tokenCreated['error'].message;
        newErrors.push(new NamedError('stripeError', errorMessage));
        setLoading(false);
      }
      setErrors(newErrors);
    }
    createTokenAndSubmitPayment();
  }, [formState]);

  if (paymentMethod != 'credit-card') {
    return null;
  }

  return (
    <StripeCreditCardForm
      onStripeFieldChange={onStripeFieldChange} errors={errors}
    />
  );
}

export const StripeProcessor = injectStripe(_StripeProcessor);
