"use client"

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

interface OrderItem {
  name: string
  quantity: number
  price: number
  image?: string
}

interface OrderData {
  id: number
  items: OrderItem[]
  subtotal: number
  shipping: number
  originalShipping?: number  // Original shipping before free shipping discount
  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

        // Calculate pricing using shared logic (matches server calculation exactly)
        const itemTotalsCents = checkoutData.order.items.map((item) => item.price_cents)
        const rawShippingCents = checkoutData.order.shipping_cost_cents
        const pricing = calculatePricing(itemTotalsCents, rawShippingCents)

        // Transform to component format
        const transformedData: OrderData = {
          id: checkoutData.order.id,
          items: checkoutData.order.items.map((item) => ({
            name: item.name,
            quantity: item.quantity,
            price: item.price_cents,
            image: item.image,
          })),
          subtotal: pricing.subtotal_cents,
          shipping: pricing.shipping_cents,
          originalShipping: pricing.shipping_cents === 0 ? pricing.original_shipping_cents : undefined,
          tax: pricing.tax_cents,
          total: pricing.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 }
}
