/**
 * Success Page
 * Displays order confirmation after successful payment
 * Automatically redirects to WooCommerce orders page after 5 seconds
 */

"use client"

import { Suspense, useState, useEffect } from "react"
import { useSearchParams } from "next/navigation"
import { CheckoutHeader } from "@/components/checkout-header"
import { OrderStatusPolling } from "@/components/order-status-polling"
import { Card } from "@/components/ui/card"
import { CheckCircle2, Package, Mail, Loader2 } from "lucide-react"
import { Separator } from "@/components/ui/separator"

// Get WooCommerce base URL from environment
const getWcBaseUrl = () => {
  if (typeof window !== 'undefined') {
    // Client-side: use public env var
    return (window as any).__WC_BASE_URL__ || ""
  }
  return ""
}

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

  const [orderData, setOrderData] = useState<any>(null)
  const [isPolling, setIsPolling] = useState(true)
  const [hasTimedOut, setHasTimedOut] = useState(false)
  const [countdown, setCountdown] = useState(5)
  const [isRedirecting, setIsRedirecting] = useState(false)

  // Countdown and redirect after payment confirmation
  useEffect(() => {
    if (orderData && !isPolling && !hasTimedOut) {
      const timer = setInterval(() => {
        setCountdown((prev) => {
          if (prev <= 1) {
            clearInterval(timer)
            setIsRedirecting(true)
            // Redirect to specific order page in WooCommerce
            const wcBaseUrl = getWcBaseUrl()
            const orderId = orderData.order_id
            const redirectUrl = wcBaseUrl 
              ? `${wcBaseUrl}/my-account/view-order/${orderId}/`
              : `/my-account/view-order/${orderId}/`
            console.log("[v0] Redirecting to:", redirectUrl)
            window.location.href = redirectUrl
            return 0
          }
          return prev - 1
        })
      }, 1000)

      return () => clearInterval(timer)
    }
  }, [orderData, isPolling, hasTimedOut])

  if (!token) {
    return (
      <div className="min-h-screen bg-texture flex items-center justify-center">
        <Card className="p-10 max-w-md text-center">
          <div className="inline-flex h-16 w-16 items-center justify-center rounded-full bg-destructive/10 mb-4">
            <svg className="h-8 w-8 text-destructive" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
          </div>
          <h1 className="text-2xl font-bold text-foreground mb-2">Invalid Request</h1>
          <p className="text-muted-foreground">Missing order information. Please contact support.</p>
        </Card>
      </div>
    )
  }

  const handleConfirmed = (data: any) => {
    setOrderData(data)
    setIsPolling(false)
  }

  const handleTimeout = () => {
    setIsPolling(false)
    setHasTimedOut(true)
  }

  return (
    <div className="min-h-screen bg-texture">
      <CheckoutHeader />

      <div className="mx-auto max-w-3xl px-6 py-16 lg:py-24">
        {isPolling ? (
          <OrderStatusPolling
            token={token}
            onConfirmed={handleConfirmed}
            onTimeout={handleTimeout}
          />
        ) : hasTimedOut ? (
          <Card className="p-10">
            <div className="text-center">
              <div className="inline-flex h-20 w-20 items-center justify-center rounded-full bg-yellow-500/10 mb-6">
                <svg className="h-10 w-10 text-yellow-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
              </div>
              <h1 className="text-3xl font-bold text-foreground mb-4">Payment Processing</h1>
              <p className="text-lg text-muted-foreground mb-6">
                Your payment is being processed. You'll receive an email confirmation shortly.
              </p>
              <p className="text-sm text-muted-foreground">
                If you don't receive confirmation within 10 minutes, please contact support.
              </p>
            </div>
          </Card>
        ) : orderData ? (
          <div className="max-w-2xl mx-auto space-y-8">
            {/* Success Header */}
            <div className="text-center">
              <div className="inline-flex h-20 w-20 items-center justify-center rounded-full bg-gradient-to-br from-green-400 to-green-600 mb-6 shadow-xl shadow-green-500/30 animate-in zoom-in duration-500">
                <CheckCircle2 className="h-11 w-11 text-white" strokeWidth={2.5} />
              </div>
              <h1 className="text-4xl md:text-5xl font-bold text-foreground mb-3 animate-in fade-in slide-in-from-bottom-4 duration-700">
                Payment Successful!
              </h1>
              <p className="text-lg text-muted-foreground animate-in fade-in slide-in-from-bottom-4 duration-700 delay-100">
                Thank you for your purchase. Your order has been confirmed.
              </p>
            </div>

            {/* Order Details Card */}
            <Card className="p-8 md:p-10 animate-in fade-in slide-in-from-bottom-4 duration-700 delay-200">
              <div className="space-y-6">
                <div className="text-center pb-4">
                  <p className="text-sm text-muted-foreground">Order Number</p>
                  <p className="text-2xl font-bold text-foreground mt-1">#{orderData.order_id}</p>
                </div>

                <Separator />

                <div className="grid gap-6 sm:grid-cols-2">
                  <div className="text-center p-4 rounded-lg bg-muted/30">
                    <Package className="h-6 w-6 text-primary mx-auto mb-2" />
                    <p className="text-sm font-medium text-foreground">Order Status</p>
                    <p className="text-sm text-muted-foreground mt-1 capitalize">{orderData.status}</p>
                  </div>

                  <div className="text-center p-4 rounded-lg bg-muted/30">
                    <Mail className="h-6 w-6 text-primary mx-auto mb-2" />
                    <p className="text-sm font-medium text-foreground">Confirmation</p>
                    <p className="text-sm text-muted-foreground mt-1">Sent to your email</p>
                  </div>
                </div>

                <Separator />

                <div>
                  <h3 className="text-lg font-semibold text-foreground mb-4 text-center">What's Next?</h3>
                  <ul className="space-y-3">
                    <li className="flex items-start gap-3">
                      <CheckCircle2 className="h-5 w-5 text-green-500 flex-shrink-0 mt-0.5" />
                      <span className="text-sm text-muted-foreground">
                        Email confirmation sent with order details
                      </span>
                    </li>
                    <li className="flex items-start gap-3">
                      <CheckCircle2 className="h-5 w-5 text-green-500 flex-shrink-0 mt-0.5" />
                      <span className="text-sm text-muted-foreground">
                        Tracking information when your order ships
                      </span>
                    </li>
                    <li className="flex items-start gap-3">
                      <CheckCircle2 className="h-5 w-5 text-green-500 flex-shrink-0 mt-0.5" />
                      <span className="text-sm text-muted-foreground">
                        Support team available for any questions
                      </span>
                    </li>
                  </ul>
                </div>
              </div>
            </Card>

            {/* Countdown Timer */}
            <div className="text-center animate-in fade-in duration-700 delay-300">
              <div className="inline-flex items-center gap-3 px-6 py-3 rounded-full bg-muted/50 border border-border/50">
                {isRedirecting ? (
                  <>
                    <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
                    <span className="text-sm font-medium text-muted-foreground">Redirecting to your orders...</span>
                  </>
                ) : (
                  <>
                    <div className="flex items-center justify-center h-7 w-7 rounded-full bg-primary text-primary-foreground text-xs font-bold">
                      {countdown}
                    </div>
                    <span className="text-sm font-medium text-muted-foreground">Redirecting to your orders</span>
                  </>
                )}
              </div>
            </div>
          </div>
        ) : null}
      </div>
    </div>
  )
}

export default function SuccessPage() {
  return (
    <Suspense
      fallback={
        <div className="min-h-screen bg-texture flex items-center justify-center">
          <div className="text-center">
            <div className="h-8 w-8 border-2 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-4" />
            <p className="text-muted-foreground">Loading...</p>
          </div>
        </div>
      }
    >
      <SuccessContent />
    </Suspense>
  )
}
