/**
 * Payment Failed Page
 * Displays when payment fails
 * 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 { Card } from "@/components/ui/card"
import { XCircle, AlertTriangle, Loader2, RefreshCcw } from "lucide-react"
import { Separator } from "@/components/ui/separator"

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

function PaymentFailedContent() {
  const searchParams = useSearchParams()
  const token = searchParams.get("token")
  const error = searchParams.get("error") || "Payment was not completed"

  const [countdown, setCountdown] = useState(5)
  const [isRedirecting, setIsRedirecting] = useState(false)

  // Countdown and redirect
  useEffect(() => {
    const timer = setInterval(() => {
      setCountdown((prev) => {
        if (prev <= 1) {
          clearInterval(timer)
          setIsRedirecting(true)
          // Redirect to WooCommerce orders page (general orders list for failures)
          const wcBaseUrl = getWcBaseUrl()
          const redirectUrl = wcBaseUrl 
            ? `${wcBaseUrl}/my-account/orders/`
            : "/my-account/orders/"
          console.log("[v0] Redirecting to:", redirectUrl)
          window.location.href = redirectUrl
          return 0
        }
        return prev - 1
      })
    }, 1000)

    return () => clearInterval(timer)
  }, [])

  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">
            <AlertTriangle className="h-8 w-8 text-destructive" />
          </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>
    )
  }

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

      <div className="mx-auto max-w-3xl px-6 py-16 lg:py-24">
          <div className="max-w-2xl mx-auto space-y-8">
          {/* Failure Header */}
          <div className="text-center">
            <div className="inline-flex h-20 w-20 items-center justify-center rounded-full bg-gradient-to-br from-red-400 to-red-600 mb-6 shadow-xl shadow-red-500/30 animate-in zoom-in duration-500">
              <XCircle 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 Failed
            </h1>
            <p className="text-lg text-muted-foreground animate-in fade-in slide-in-from-bottom-4 duration-700 delay-100">
              Your payment could not be processed. Don't worry, your cart is still intact.
            </p>
          </div>

          {/* Failure 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">Error Message</p>
                <p className="text-base text-foreground mt-1">{error}</p>
              </div>

              <Separator />

              <div className="space-y-4">
                <div className="text-center p-4 rounded-lg bg-green-500/5 border border-green-500/20">
                  <RefreshCcw className="h-6 w-6 text-green-600 mx-auto mb-2" />
                  <p className="text-sm font-medium text-foreground mb-1">Your Cart is Safe</p>
                  <p className="text-sm text-muted-foreground">
                    All items remain in your cart. You can try again anytime.
                  </p>
                </div>
              </div>

              <Separator />

              <div>
                <h3 className="text-lg font-semibold text-foreground mb-4 text-center">Common Solutions</h3>
                <ul className="space-y-3">
                  <li className="flex items-start gap-3">
                    <div className="h-6 w-6 rounded-full bg-primary/10 flex items-center justify-center flex-shrink-0 mt-0.5">
                      <span className="text-xs font-bold text-primary">1</span>
                    </div>
                    <span className="text-sm text-muted-foreground">
                      Check your card details and try again
                    </span>
                  </li>
                  <li className="flex items-start gap-3">
                    <div className="h-6 w-6 rounded-full bg-primary/10 flex items-center justify-center flex-shrink-0 mt-0.5">
                      <span className="text-xs font-bold text-primary">2</span>
                    </div>
                    <span className="text-sm text-muted-foreground">
                      Ensure you have sufficient funds available
                    </span>
                  </li>
                  <li className="flex items-start gap-3">
                    <div className="h-6 w-6 rounded-full bg-primary/10 flex items-center justify-center flex-shrink-0 mt-0.5">
                      <span className="text-xs font-bold text-primary">3</span>
                    </div>
                    <span className="text-sm text-muted-foreground">
                      Contact your bank if the problem persists
                    </span>
                  </li>
                  <li className="flex items-start gap-3">
                    <div className="h-6 w-6 rounded-full bg-primary/10 flex items-center justify-center flex-shrink-0 mt-0.5">
                      <span className="text-xs font-bold text-primary">4</span>
                    </div>
                    <span className="text-sm text-muted-foreground">
                      Try using a different payment method
                    </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>
      </div>
    </div>
  )
}

export default function PaymentFailedPage() {
  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>
      }
    >
      <PaymentFailedContent />
    </Suspense>
  )
}

