"use client"

import { useState } from "react"
import { PayPalButtons, usePayPalScriptReducer } from "@paypal/react-paypal-js"
import { Skeleton } from "@/components/ui/skeleton"

interface PayPalPaymentFormProps {
  paypalOrderId: string
  token: string
  onApprove: (captureId: string) => void
  onError: (error: string) => void
}

export function PayPalPaymentForm({ paypalOrderId, token, onApprove, onError }: PayPalPaymentFormProps) {
  const [{ isPending }] = usePayPalScriptReducer()
  const [isCapturing, setIsCapturing] = useState(false)

  if (isPending) {
    return <PayPalPaymentFormSkeleton />
  }

  return (
    <div className="relative">
      {isCapturing && (
        <div className="absolute inset-0 flex items-center justify-center bg-card/50 backdrop-blur-sm rounded-xl z-10">
          <div className="flex flex-col items-center gap-3">
            <div className="h-8 w-8 border-2 border-primary border-t-transparent rounded-full animate-spin" />
            <p className="text-sm text-muted-foreground">Processing payment...</p>
          </div>
        </div>
      )}
      <PayPalButtons
        style={{
          layout: "vertical",
          color: "gold",
          shape: "rect",
          label: "paypal",
          height: 55,
        }}
        createOrder={async () => {
          // Return the pre-created PayPal order ID
          return paypalOrderId
        }}
        onApprove={async (data) => {
          try {
            setIsCapturing(true)
            console.log("[v0] PayPal onApprove, capturing order:", data.orderID)

            const response = await fetch("/api/paypal/capture-order", {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({
                token,
                paypal_order_id: data.orderID,
              }),
            })

            const result = await response.json()

            if (!response.ok || !result.success) {
              throw new Error(result.error?.message || "Failed to capture PayPal payment")
            }

            console.log("[v0] PayPal capture successful:", result.capture_id)
            onApprove(result.capture_id)
          } catch (err) {
            console.error("[v0] PayPal capture error:", err)
            onError(err instanceof Error ? err.message : "Payment capture failed")
          } finally {
            setIsCapturing(false)
          }
        }}
        onError={(err) => {
          console.error("[v0] PayPal button error:", err)
          onError("PayPal encountered an error. Please try again.")
        }}
        onCancel={() => {
          console.log("[v0] PayPal payment cancelled by user")
        }}
      />
    </div>
  )
}

export function PayPalPaymentFormSkeleton() {
  return (
    <div className="rounded-xl border border-border/50 bg-card p-8 space-y-4">
      <Skeleton className="h-[55px] w-full rounded-lg" />
      <Skeleton className="h-[55px] w-full rounded-lg" />
      <div className="text-center pt-2">
        <Skeleton className="h-4 w-48 mx-auto" />
      </div>
    </div>
  )
}
