"use client"

import { useState, useEffect } from "react"
import { useSearchParams } from "next/navigation"
import type { CheckoutSessionResponse } from "@/lib/types/api"

interface OrderData {
  id: number
  tax: number
  total: number
  currency: string
  email: string
}

export function useCheckoutData() {
  const searchParams = useSearchParams()
  const token = searchParams.get("token")

  const [orderData, setOrderData] = useState<OrderData | undefined>(undefined)
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    const fetchOrderData = async () => {
      if (!token) {
        setError("Missing checkout token. Please use a valid checkout link.")
        setIsLoading(false)
        return
      }

      try {
        setIsLoading(true)
        setError(null)

        const response = await fetch(`/api/checkout-session?token=${encodeURIComponent(token)}`)
        const data = await response.json()

        if (!response.ok || !data.success) {
          throw new Error(data.error?.message || "Failed to load checkout session")
        }

        const checkoutData = data as CheckoutSessionResponse

        // Use server-calculated totals directly (total already includes shipping)
        const transformedData: OrderData = {
          id: checkoutData.order.id,
          tax: checkoutData.order.tax_cents,
          total: checkoutData.order.total_cents,
          currency: checkoutData.order.currency,
          email: checkoutData.order.email,
        }

        setOrderData(transformedData)
      } catch (err) {
        // Client-side logging - keep console.error for browser debugging
        console.error("[v0] Failed to fetch checkout data:", err)
        setError(err instanceof Error ? err.message : "Failed to load order data")
      } finally {
        setIsLoading(false)
      }
    }

    fetchOrderData()
  }, [token])

  return { orderData, isLoading, error, token }
}
