"use client"

import { useState } from "react"
import { useSearchParams, useRouter } from "next/navigation"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { CheckCircle, CreditCard, ArrowRight } from "lucide-react"
import { LoadingSpinner } from "@/components/loading-spinner"
import { toast } from "@/lib/toast"

export default function DemoPaymentPage() {
  const searchParams = useSearchParams()
  const router = useRouter()
  const [isProcessing, setIsProcessing] = useState(false)
  const [paymentComplete, setPaymentComplete] = useState(false)

  const reference = searchParams.get("reference")
  const email = searchParams.get("email")
  const amount = searchParams.get("amount")
  const currency = searchParams.get("currency")
  const studentType = searchParams.get("studentType")

  const handleDemoPayment = async () => {
    setIsProcessing(true)

    // Simulate payment processing delay
    await new Promise((resolve) => setTimeout(resolve, 2000))

    try {
      // Call the payment callback to complete the voucher creation
      const response = await fetch("/api/payments/callback", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          reference,
          status: "success",
          demo_mode: true,
        }),
      })

      const data = await response.json()

      if (data.success) {
        setPaymentComplete(true)
        toast.success("Payment completed successfully!")

        // Redirect to login after a short delay
        setTimeout(() => {
          router.push("/login?message=voucher_created")
        }, 3000)
      } else {
        throw new Error(data.message || "Payment processing failed")
      }
    } catch (error) {
      console.error("[v0] Demo payment error:", error)
      toast.error("Payment processing failed. Please try again.")
    } finally {
      setIsProcessing(false)
    }
  }

  if (paymentComplete) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center p-4">
        <Card className="w-full max-w-md">
          <CardHeader className="text-center">
            <div className="mx-auto w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mb-4">
              <CheckCircle className="w-8 h-8 text-green-600" />
            </div>
            <CardTitle className="text-green-600">Payment Successful!</CardTitle>
          </CardHeader>
          <CardContent className="text-center space-y-4">
            <p className="text-muted-foreground">Your voucher has been created and sent to your email.</p>
            <p className="text-sm text-muted-foreground">Redirecting to login page...</p>
            <LoadingSpinner size="sm" />
          </CardContent>
        </Card>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-background flex items-center justify-center p-4">
      <Card className="w-full max-w-md">
        <CardHeader className="text-center">
          <div className="mx-auto w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mb-4">
            <CreditCard className="w-8 h-8 text-blue-600" />
          </div>
          <CardTitle>Demo Payment Gateway</CardTitle>
        </CardHeader>
        <CardContent className="space-y-6">
          <div className="space-y-3">
            <div className="flex justify-between">
              <span className="text-muted-foreground">Email:</span>
              <span className="font-medium">{email}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-muted-foreground">Amount:</span>
              <span className="font-medium">
                {currency === "USD" ? "$" : "₵"}
                {amount}
              </span>
            </div>
            <div className="flex justify-between">
              <span className="text-muted-foreground">Student Type:</span>
              <span className="font-medium capitalize">{studentType}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-muted-foreground">Reference:</span>
              <span className="font-medium text-xs">{reference}</span>
            </div>
          </div>

          <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
            <p className="text-sm text-yellow-800">
              <strong>Demo Mode:</strong> This is a simulated payment for demonstration purposes. No real payment will
              be processed.
            </p>
          </div>

          <Button onClick={handleDemoPayment} disabled={isProcessing} className="w-full">
            {isProcessing ? (
              <>
                <LoadingSpinner size="sm" className="mr-2" />
                Processing Payment...
              </>
            ) : (
              <>
                Complete Demo Payment
                <ArrowRight className="w-4 h-4 ml-2" />
              </>
            )}
          </Button>

          <p className="text-xs text-center text-muted-foreground">
            This demo will create a voucher and redirect you to the login page
          </p>
        </CardContent>
      </Card>
    </div>
  )
}
