import { useMutation } from '@apollo/client';
import { useStripe } from '@stripe/react-stripe-js';
import { handlePaymentIntent, handleSetupIntent } from './handlers';
import { CREATE_SUBSCRIPTION } from './schema/mutations';
import {
  CreateSubscriptionMutation,
  CreateSubscriptionMutationVariables,
} from 'types/graphql';

export function useCreateSubscription() {
  const stripe = useStripe();
  const [create] = useMutation<
    CreateSubscriptionMutation,
    CreateSubscriptionMutationVariables
  >(CREATE_SUBSCRIPTION);

  const subscribe = async (
    planId: string,
    billingCycle: string,
    paymentMethodId: string
  ) => {
    try {
      const variables = {
        stripePaymentId: paymentMethodId,
        productPackageName: planId,
        billingCycle: billingCycle,
      };

      const { data } = await create({ variables });

      if (!data?.subscription) throw new Error('Cannot create subscription');

      const { paymentIntentStatus, intentType, clientSecret } =
        data.subscription;

      if (paymentIntentStatus === 'succeeded') {
        return { status: paymentIntentStatus };
      } else if (paymentIntentStatus === 'requires_payment_method') {
        // If attaching this card to a Customer object succeeds,
        // but attempts to charge the customer fail, you
        // get a requires_payment_method error.
        return {
          error: new Error('Your card was declined'),
          status: paymentIntentStatus,
        };
      } else if (paymentIntentStatus === 'requires_action') {
        const handleIntent =
          intentType === 'payment' ? handlePaymentIntent : handleSetupIntent;

        const result = await handleIntent(stripe!)(
          clientSecret,
          paymentMethodId
        );

        return result;
      } else {
        return { status: paymentIntentStatus };
      }
    } catch (error) {
      console.log('catch', error);
      throw error;
    }
  };

  return subscribe;
}
