"use client"

import type React from "react"
import Image from "next/image"
import { useState } from "react"
import Link from "next/link"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { ArrowLeft, Shield, Mail, Globe, Users } from "lucide-react"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { toast } from "@/lib/toast"
import { LoadingSpinner } from "@/components/loading-spinner"

declare global {
  interface Window {
    PaystackPop: {
      setup: (options: {
        key: string
        email: string
        amount: number
        currency: string
        ref: string
        callback: (response: any) => void
        onClose: () => void
      }) => {
        openIframe: () => void
      }
    }
  }
}

export default function PurchaseVoucherPage() {
  const [email, setEmail] = useState("")
  const [studentType, setStudentType] = useState<"local" | "foreign">("local")
  const [isLoading, setIsLoading] = useState(false)
  const [errors, setErrors] = useState<{ email?: string }>({})
  const [paystackLoaded, setPaystackLoaded] = useState(false)

  const loadPaystackScript = () => {
    return new Promise<void>((resolve, reject) => {
      if (window.PaystackPop) {
        resolve()
        return
      }

      const script = document.createElement("script")
      script.src = "https://js.paystack.co/v1/inline.js"
      script.onload = () => {
        setPaystackLoaded(true)
        resolve()
      }
      script.onerror = () => reject(new Error("Failed to load Paystack script"))
      document.head.appendChild(script)
    })
  }

  const validateForm = () => {
    const newErrors: typeof errors = {}

    if (!email.trim()) {
      newErrors.email = "Email address is required"
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim())) {
      newErrors.email = "Please enter a valid email address"
    }

    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    if (!validateForm()) {
      toast.error("Please enter a valid email address")
      return
    }

    setIsLoading(true)
    setErrors({})

    try {
      const amount = studentType === "local" ? 25000 : 5000 // Amount in kobo/cents
      const currency = studentType === "local" ? "GHS" : "USD"
      const reference = `FU_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`

      console.log("[v0] Initializing payment with:", { amount, currency, reference, email: email.trim() })

      toast.loading("Loading payment gateway...")

      await loadPaystackScript()

      const publicKey = "pk_test_36df1d00d3d40c3850d129c69f950daa6b95ed93"

      const handler = window.PaystackPop.setup({
        key: publicKey,
        email: email.trim(),
        amount: amount,
        currency: currency,
        ref: reference,
        callback: async (response) => {
          console.log("[v0] Payment successful:", response)

          // Store student type for callback
          localStorage.setItem("studentType", studentType)
          localStorage.setItem("userEmail", email.trim())
          localStorage.setItem("paymentReference", response.reference)

          toast.success("Payment successful! Verifying...")

          // Verify payment on server
          try {
            const verifyResponse = await fetch("/api/payments/verify", {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
              },
              body: JSON.stringify({
                reference: response.reference,
                email: email.trim(),
                studentType,
              }),
            })

            const verifyData = await verifyResponse.json()

            if (verifyData.success) {
              toast.success("Payment verified! Redirecting...")
              window.location.href = `/payment/callback?reference=${response.reference}&status=success`
            } else {
              throw new Error(verifyData.message || "Payment verification failed")
            }
          } catch (error) {
            console.error("[v0] Payment verification error:", error)
            toast.error("Payment verification failed. Please contact support.")
          }

          setIsLoading(false)
        },
        onClose: () => {
          console.log("[v0] Payment popup closed")
          toast.error("Payment cancelled")
          setIsLoading(false)
        },
      })

      handler.openIframe()
    } catch (error) {
      console.error("[v0] Payment initialization error:", error)
      toast.error("Failed to initialize payment. Please try again.")
      setIsLoading(false)
    }
  }

  return (
    <div className="min-h-screen bg-background">
      <div className="container mx-auto px-4 py-8">
        <div className="max-w-4xl mx-auto space-y-6">
          {/* Header */}
          <div className="text-center">
            <Link
              href="/"
              className="inline-flex items-center gap-2 mb-6 text-muted-foreground hover:text-foreground transition-colors"
              aria-label="Back to home page"
            >
              <ArrowLeft className="h-4 w-4" />
              <span className="text-sm">Back to Home</span>
            </Link>
            <div className="flex items-center justify-center gap-3 mb-4">
              <Image
                src="/images/fanaka-logo.png"
                alt="Fanaka International University College Logo"
                width={40}
                height={40}
                className="h-10 w-auto"
              />
              <div className="text-center">
                <span className="text-2xl font-black text-primary block leading-tight">Fanaka International</span>
                <span className="text-xl font-black text-primary block leading-tight">University College</span>
              </div>
            </div>
            <h1 className="text-3xl font-bold text-primary">Purchase Application Voucher</h1>
            <p className="text-muted-foreground">Choose your student type and secure your application voucher</p>
          </div>

          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Globe className="h-5 w-5 text-accent" aria-hidden="true" />
                Select Student Type
              </CardTitle>
              <CardDescription>Choose whether you are a local or international student</CardDescription>
            </CardHeader>
            <CardContent>
              <Tabs value={studentType} onValueChange={(value) => setStudentType(value as "local" | "foreign")}>
                <TabsList className="grid w-full grid-cols-2" role="tablist">
                  <TabsTrigger value="local" className="flex items-center gap-2" role="tab">
                    <Users className="h-4 w-4" aria-hidden="true" />
                    Local Student
                  </TabsTrigger>
                  <TabsTrigger value="foreign" className="flex items-center gap-2" role="tab">
                    <Globe className="h-4 w-4" aria-hidden="true" />
                    International Student
                  </TabsTrigger>
                </TabsList>

                <TabsContent value="local" className="mt-6">
                  <Card>
                    <CardContent className="pt-6">
                      <div className="space-y-4">
                        <div className="flex justify-between items-center p-4 bg-muted rounded-lg">
                          <span className="font-medium">Local Student Voucher Fee</span>
                          <span className="text-3xl font-bold text-accent">₵250</span>
                        </div>
                        <div className="space-y-2 text-sm text-muted-foreground">
                          <p>✓ For Ghanaian citizens and residents</p>
                          <p>✓ Complete access to all application sections</p>
                          <p>✓ Local document requirements</p>
                          <p>✓ Ghana-specific program options</p>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                </TabsContent>

                <TabsContent value="foreign" className="mt-6">
                  <Card>
                    <CardContent className="pt-6">
                      <div className="space-y-4">
                        <div className="flex justify-between items-center p-4 bg-muted rounded-lg">
                          <span className="font-medium">International Student Voucher Fee</span>
                          <span className="text-3xl font-bold text-accent">$50</span>
                        </div>
                        <div className="space-y-2 text-sm text-muted-foreground">
                          <p>✓ For international students</p>
                          <p>✓ Additional passport/visa documentation</p>
                          <p>✓ International program options</p>
                          <p>✓ Foreign credential evaluation support</p>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                </TabsContent>
              </Tabs>
            </CardContent>
          </Card>

          {/* Voucher Information */}
          <Card>
            <CardHeader>
              <CardTitle>Application Voucher</CardTitle>
              <CardDescription>One-time payment for complete application access</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                <div className="flex justify-between items-center p-4 bg-muted rounded-lg">
                  <span className="font-medium">Application Voucher Fee</span>
                  <span className="text-2xl font-bold text-accent">{studentType === "local" ? "₵250" : "$50"}</span>
                </div>
                <div className="space-y-2 text-sm text-muted-foreground">
                  {studentType === "local" ? (
                    <>
                      <p>✓ Complete access to all application sections</p>
                      <p>✓ Save and edit your application multiple times</p>
                      <p>✓ Upload required documents</p>
                      <p>✓ Submit your final application</p>
                      <p>✓ Track your admission status</p>
                    </>
                  ) : (
                    <>
                      <p>✓ Complete access to all application sections</p>
                      <p>✓ Save and edit your application multiple times</p>
                      <p>✓ Upload required documents</p>
                      <p>✓ Submit your final application</p>
                      <p>✓ Track your admission status</p>
                    </>
                  )}
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Payment Form */}
          <Card>
            <CardHeader>
              <CardTitle>Payment Information</CardTitle>
              <CardDescription>Enter your email to receive voucher details after payment</CardDescription>
            </CardHeader>
            <CardContent>
              <form onSubmit={handleSubmit} className="space-y-4" noValidate>
                <div className="space-y-2">
                  <Label htmlFor="email">
                    Email Address
                    <span className="text-red-500 ml-1" aria-label="required">
                      *
                    </span>
                  </Label>
                  <Input
                    id="email"
                    type="email"
                    placeholder="Enter your email address"
                    value={email}
                    onChange={(e) => {
                      setEmail(e.target.value)
                      if (errors.email) {
                        setErrors((prev) => ({ ...prev, email: undefined }))
                      }
                    }}
                    required
                    aria-invalid={errors.email ? "true" : "false"}
                    aria-describedby={errors.email ? "email-error email-help" : "email-help"}
                    className={errors.email ? "border-red-500 focus:border-red-500" : ""}
                  />
                  <p id="email-help" className="text-xs text-muted-foreground">
                    Your voucher serial number and PIN will be sent to this email
                  </p>
                  {errors.email && (
                    <p id="email-error" className="text-sm text-red-600" role="alert">
                      {errors.email}
                    </p>
                  )}
                </div>
                <Button
                  type="submit"
                  className="w-full bg-accent hover:bg-accent/90 text-lg py-6"
                  disabled={isLoading}
                  aria-describedby={isLoading ? "payment-status" : undefined}
                >
                  {isLoading ? (
                    <>
                      <LoadingSpinner size="sm" className="mr-2" />
                      Processing Payment...
                    </>
                  ) : (
                    `Pay ${studentType === "local" ? "₵250" : "$50"} with Paystack`
                  )}
                </Button>
                {isLoading && (
                  <p id="payment-status" className="sr-only">
                    Processing payment request, please wait
                  </p>
                )}
              </form>
            </CardContent>
          </Card>

          {/* Security Information */}
          <Card>
            <CardContent className="pt-6">
              <div className="flex items-start gap-3">
                <Shield className="h-5 w-5 text-green-600 mt-0.5" />
                <div className="space-y-1">
                  <h3 className="font-medium">Secure Payment</h3>
                  <p className="text-sm text-muted-foreground">
                    Your payment is processed securely through Paystack. We do not store your payment information.
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* What Happens Next */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Mail className="h-5 w-5 text-accent" />
                What Happens Next?
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-3">
                <div className="flex items-start gap-3">
                  <div className="w-6 h-6 rounded-full bg-accent text-accent-foreground text-xs flex items-center justify-center font-medium">
                    1
                  </div>
                  <div>
                    <p className="font-medium">Payment Confirmation</p>
                    <p className="text-sm text-muted-foreground">You'll receive an immediate payment confirmation</p>
                  </div>
                </div>
                <div className="flex items-start gap-3">
                  <div className="w-6 h-6 rounded-full bg-accent text-accent-foreground text-xs flex items-center justify-center font-medium">
                    2
                  </div>
                  <div>
                    <p className="font-medium">Voucher Details</p>
                    <p className="text-sm text-muted-foreground">
                      Your unique serial number and PIN will be emailed to you
                    </p>
                  </div>
                </div>
                <div className="flex items-start gap-3">
                  <div className="w-6 h-6 rounded-full bg-accent text-accent-foreground text-xs flex items-center justify-center font-medium">
                    3
                  </div>
                  <div>
                    <p className="font-medium">Start Your Application</p>
                    <p className="text-sm text-muted-foreground">
                      Use your voucher credentials to login and begin your application
                    </p>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Already Have Voucher */}
          <div className="text-center">
            <p className="text-muted-foreground">
              Already have a voucher?{" "}
              <Link href="/login" className="text-accent hover:underline font-medium">
                Login to Portal
              </Link>
            </p>
          </div>
        </div>
      </div>
    </div>
  )
}
