/**
 * Member Payment Management Composable
 * Handles payment setup and subscription creation for pending payment members
 */

export const useMemberPayment = () => {
  const { memberData, checkMemberStatus } = useAuth()
  const { initializeHelcimPay, verifyPayment, cleanup: cleanupHelcimPay } =
    useHelcimPay()

  const isProcessingPayment = ref(false)
  const paymentError = ref(null)
  const paymentSuccess = ref(false)

  const customerId = ref('')
  const customerCode = ref('')

  /**
   * Initiate payment setup for a member with pending_payment status
   * This is the main entry point called from "Complete Payment" buttons
   */
  const initiatePaymentSetup = async () => {
    isProcessingPayment.value = true
    paymentError.value = null
    paymentSuccess.value = false

    try {
      // Step 1: Get or create Helcim customer
      await getOrCreateCustomer()

      // Step 2: Initialize Helcim payment with $0 for card verification
      await initializeHelcimPay(
        customerId.value,
        customerCode.value,
        0,
      )

      // Step 3: Show payment modal and get payment result
      const paymentResult = await verifyPayment()
      console.log('Payment result:', paymentResult)

      if (!paymentResult.success) {
        throw new Error('Payment verification failed')
      }

      // Step 4: Verify payment on backend
      const verifyResult = await $fetch('/api/helcim/verify-payment', {
        method: 'POST',
        body: {
          cardToken: paymentResult.cardToken,
          customerId: customerId.value,
        },
      })

      if (!verifyResult.success) {
        throw new Error('Payment verification failed on backend')
      }

      // Step 5: Create subscription with proper contribution tier
      const subscriptionResponse = await $fetch('/api/helcim/subscription', {
        method: 'POST',
        body: {
          customerId: customerId.value,
          customerCode: customerCode.value,
          contributionTier: memberData.value?.contributionTier || '5',
          cardToken: paymentResult.cardToken,
        },
      })

      if (!subscriptionResponse.success) {
        throw new Error('Subscription creation failed')
      }

      // Step 6: Payment successful - refresh member data
      paymentSuccess.value = true
      await checkMemberStatus()

      // Clear success message after 3 seconds
      setTimeout(() => {
        paymentSuccess.value = false
      }, 3000)

      return {
        success: true,
        message: 'Payment completed successfully!',
      }
    } catch (error) {
      console.error('Payment setup error:', error)
      paymentError.value =
        error.message || 'Payment setup failed. Please try again.'
      throw error
    } finally {
      isProcessingPayment.value = false
      cleanupHelcimPay()
    }
  }

  /**
   * Get or create Helcim customer for member
   */
  const getOrCreateCustomer = async () => {
    try {
      if (!memberData.value?.helcimCustomerId) {
        // Create new customer
        const customerResponse = await $fetch(
          '/api/helcim/get-or-create-customer',
          {
            method: 'POST',
          },
        )

        customerId.value = customerResponse.customerId
        customerCode.value = customerResponse.customerCode

        console.log(
          'Created new Helcim customer:',
          customerId.value,
        )
      } else {
        // Get customer code from existing customer
        const customerResponse = await $fetch(
          '/api/helcim/customer-code',
        )
        customerId.value = customerResponse.customerId
        customerCode.value = customerResponse.customerCode

        console.log(
          'Using existing Helcim customer:',
          customerId.value,
        )
      }
    } catch (error) {
      console.error('Failed to get or create customer:', error)
      throw new Error('Failed to initialize payment. Please try again.')
    }
  }

  /**
   * Complete payment from status banner
   * Entry point for clicking "Complete Payment" from any page
   */
  const completePayment = async () => {
    try {
      await initiatePaymentSetup()
      return true
    } catch (error) {
      console.error('Payment failed:', error)
      return false
    }
  }

  const resetPaymentState = () => {
    isProcessingPayment.value = false
    paymentError.value = null
    paymentSuccess.value = false
  }

  return {
    isProcessingPayment: readonly(isProcessingPayment),
    paymentError: readonly(paymentError),
    paymentSuccess: readonly(paymentSuccess),
    initiatePaymentSetup,
    completePayment,
    resetPaymentState,
  }
}
