import { Stripe } from '@stripe/stripe-js';
import { useMutation, gql } from '@apollo/client';

import {
  SetupPaymentMethodMutation,
  SetupPaymentMethodMutationVariables,
} from 'types/graphql';
import { handleSetupIntent } from 'components/billing/handlers';

export const SETUP_PAYMENT_METHOD = gql`
  mutation SETUP_PAYMENT_METHOD($stripePaymentId: String!) {
    setupIntent(stripePaymentId: $stripePaymentId) {
      clientSecret
      lastError
      status
    }
  }
`;

export function useSetupIntent(stripe: Stripe) {
  const [setupPaymentIntent] = useMutation<
    SetupPaymentMethodMutation,
    SetupPaymentMethodMutationVariables
  >(SETUP_PAYMENT_METHOD);

  async function setupCard(paymentMethodId: string) {
    try {
      const result = await setupPaymentIntent({
        variables: { stripePaymentId: paymentMethodId },
      });
      const setupIntent = result.data?.setupIntent;

      if (!setupIntent) throw new Error('Cannot setup payment intent');

      if (setupIntent.status === 'succeeded') {
        return { status: setupIntent.status };
      } else if (setupIntent.status === 'requires_action') {
        const result = await handleSetupIntent(stripe!)(
          setupIntent.clientSecret,
          paymentMethodId
        );
        return result;
      } else {
        return {
          error: new Error(`Card setup status: ${setupIntent!.status}`),
          status: setupIntent!.status,
        };
      }
    } catch (error) {
      console.log(error);
      throw error;
    }
  }

  return setupCard;
}
