/**
 * Stripe payment processing hook
 * Manages payment intent creation and payment confirmation
 */

"use client"

import { useState, useCallback } from "react"
import { useStripe, useElements } from "@stripe/react-stripe-js"
import type { PaymentState, PaymentError } from "@/lib/types/checkout"
import type { BillingAddress, ShippingAddress } from "@/lib/types/checkout"

interface UseStripePaymentParams {
  token: string
  onSuccess?: (paymentIntentId: string) => void
  onError?: (error: PaymentError) => void
}

export function useStripePayment({ token, onSuccess, onError }: UseStripePaymentParams) {
  const stripe = useStripe()
  const elements = useElements()

  const [paymentState, setPaymentState] = useState<PaymentState>("idle")
  const [error, setError] = useState<PaymentError | null>(null)

  const processPayment = useCallback(
    async (billingAddress: BillingAddress, shippingAddress: ShippingAddress | null) => {
      if (!stripe || !elements) {
        const err: PaymentError = {
          code: "STRIPE_NOT_LOADED",
          message: "Stripe has not loaded yet. Please try again.",
        }
        setError(err)
        onError?.(err)
        return
      }

      try {
        setPaymentState("processing")
        setError(null)

        console.log("[v0] Starting payment confirmation")
        
        // First, submit the elements to validate all fields
        const { error: submitError } = await elements.submit()
        
        if (submitError) {
          console.error("[v0] Elements submit error:", submitError)
          throw new Error(submitError.message || "Please check your payment details")
        }

        console.log("[v0] Elements submitted successfully, confirming payment...")

        // Confirm payment with Stripe
        // The elements object already has the Payment Element mounted with the correct clientSecret
        const { error: confirmError } = await stripe.confirmPayment({
          elements,
          confirmParams: {
            return_url: `${window.location.origin}/success?token=${token}`,
          },
        })
        
        console.log("[v0] Confirm payment completed")

        // This point is only reached if there's an immediate error
        // Successful payments will redirect to return_url
        if (confirmError) {
          const err: PaymentError = {
            code: confirmError.code || "PAYMENT_FAILED",
            message: confirmError.message || "Payment failed. Please try again.",
            details: confirmError,
          }
          setError(err)
          setPaymentState("failed")
          onError?.(err)
          
          // Redirect to failure page after a short delay
          setTimeout(() => {
            window.location.href = `/payment-failed?token=${token}&error=${encodeURIComponent(err.message)}`
          }, 2000)
        }
      } catch (err) {
        const paymentError: PaymentError = {
          code: "PAYMENT_ERROR",
          message: err instanceof Error ? err.message : "An unexpected error occurred",
          details: err,
        }
        setError(paymentError)
        setPaymentState("failed")
        onError?.(paymentError)
      }
    },
    [stripe, elements, token, onSuccess, onError],
  )

  return {
    processPayment,
    paymentState,
    error,
    isProcessing: paymentState === "creating_intent" || paymentState === "processing",
  }
}


