import React, {forwardRef, useContext, FunctionComponentElement} from 'react';
import PaystackProvider from './paystack-provider';
import {PaystackCallbacks, PaystackProps} from './types';
import PaystackContext from './paystack-context';

interface PaystackConsumerProps extends PaystackProps, PaystackCallbacks {
  children: (arg: Record<string, any>) => any;
}

const PaystackConsumerChild = ({
  children,
  ref,
}: {
  children: any;
  ref: any;
}): FunctionComponentElement<any> => {
  const {config, initializePayment, onSuccess, onClose, onError, onLoad} = useContext(PaystackContext);

  const completeInitializePayment = (): void => initializePayment({config, onSuccess, onClose, onError, onLoad});
  return children({initializePayment: completeInitializePayment, ref});
};

// eslint-disable-next-line react/display-name
const PaystackConsumer = forwardRef(
  (
    {children, onSuccess: paraSuccess, onClose: paraClose, onError: paraError, onLoad: paraLoad, ...others}: PaystackConsumerProps,
    ref: any,
  ): JSX.Element => {
    const onSuccess = paraSuccess ? paraSuccess : (): any => null;
    const onClose = paraClose ? paraClose : (): any => null;
    const onError = paraError ? paraError : (): any => null;
    const onLoad = paraLoad ? paraLoad : (): any => null;
    return (
      <PaystackProvider {...others} onSuccess={onSuccess} onClose={onClose} onError={onError} onLoad={onLoad}>
        <PaystackConsumerChild ref={ref}>{children}</PaystackConsumerChild>
      </PaystackProvider>
    );
  },
);

export default PaystackConsumer;
