/**
 * Order Status Polling Component
 * Shows animated loading state while polling for payment confirmation
 */

"use client"

import { useEffect, useState } from "react"
import { Card } from "@/components/ui/card"
import { CheckCircle2, Loader2, XCircle } from "lucide-react"

interface OrderStatusPollingProps {
  token: string
  onConfirmed: (orderData: any) => void
  onTimeout: () => void
  maxAttempts?: number
}

export function OrderStatusPolling({
  token,
  onConfirmed,
  onTimeout,
  maxAttempts = 15, // 15 attempts * 2 seconds = 30 seconds
}: OrderStatusPollingProps) {
  const [attempts, setAttempts] = useState(0)
  const [status, setStatus] = useState<"polling" | "confirmed" | "timeout">("polling")

  useEffect(() => {
    if (!token || status !== "polling") return

    const pollStatus = async () => {
      try {
        const response = await fetch(`/api/order-status?token=${encodeURIComponent(token)}`)
        const data = await response.json()

        if (response.ok && data.success && data.paid) {
          setStatus("confirmed")
          onConfirmed(data)
          return true
        }

        return false
      } catch (error) {
        // Client-side logging - keep console.error for browser debugging
        console.error("[v0] Failed to poll order status:", error)
        return false
      }
    }

    const interval = setInterval(async () => {
      setAttempts((prev) => {
        const nextAttempt = prev + 1

        if (nextAttempt >= maxAttempts) {
          clearInterval(interval)
          setStatus("timeout")
          onTimeout()
          return prev
        }

        return nextAttempt
      })

      const confirmed = await pollStatus()
      if (confirmed) {
        clearInterval(interval)
      }
    }, 2000)

    // Initial immediate check
    pollStatus().then((confirmed) => {
      if (confirmed) {
        clearInterval(interval)
      }
    })

    return () => clearInterval(interval)
  }, [token, status, maxAttempts, onConfirmed, onTimeout])

  return (
    <Card className="p-10 text-center" role="status" aria-live="polite">
      <div className="flex flex-col items-center gap-6">
        {status === "polling" && (
          <>
            <div className="relative">
              <div className="h-20 w-20 rounded-full border-4 border-primary/20 flex items-center justify-center">
                <Loader2 className="h-10 w-10 text-primary animate-spin" aria-hidden="true" />
              </div>
            </div>
            <div>
              <h2 className="text-2xl font-bold text-foreground mb-2">Confirming Payment</h2>
              <p className="text-muted-foreground">
                Please wait while we verify your payment...
              </p>
            </div>
          </>
        )}

        {status === "confirmed" && (
          <>
            <div className="h-20 w-20 rounded-full bg-green-500/10 flex items-center justify-center">
              <CheckCircle2 className="h-10 w-10 text-green-500" />
            </div>
            <div>
              <h2 className="text-2xl font-bold text-foreground mb-2">Payment Confirmed!</h2>
              <p className="text-muted-foreground">Loading your order details...</p>
            </div>
          </>
        )}

        {status === "timeout" && (
          <>
            <div className="h-20 w-20 rounded-full bg-yellow-500/10 flex items-center justify-center">
              <XCircle className="h-10 w-10 text-yellow-500" />
            </div>
            <div>
              <h2 className="text-2xl font-bold text-foreground mb-2">Taking Longer Than Expected</h2>
              <p className="text-muted-foreground">
                Your payment may still be processing. Please check your email for confirmation.
              </p>
            </div>
          </>
        )}
      </div>
    </Card>
  )
}

