"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import {
  Loader2,
  Lock,
  CheckCircle,
  Download,
  ShoppingCart,
} from "lucide-react"
import { useToast } from "@/hooks/use-toast"
import Link from "next/link"

interface DigitalProductActionsProps {
  productId: string
  productSlug?: string | null
  title: string
  price: number
  email?: string | null
  userId?: string | null
  isAuthenticated: boolean
  alreadyPurchased: boolean
  purchaseReferralCode?: string | null
  sharerReferralCode?: string | null
}

export function DigitalProductActions({
  productId,
  productSlug,
  title,
  price,
  email,
  userId,
  isAuthenticated,
  alreadyPurchased,
  purchaseReferralCode,
}: DigitalProductActionsProps) {
  const { toast } = useToast()
  const [open, setOpen] = useState(false)
  const [buying, setBuying] = useState(false)

  const handleBuy = async () => {
    if (!isAuthenticated || !userId) return

    setBuying(true)
    try {
      const res = await fetch("/api/paystack/initialize-marketplace", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          email: email || undefined,
          userId,
          productId,
          referralCode: purchaseReferralCode || undefined,
        }),
      })

      const data = await res.json()
      if (!res.ok) throw new Error(data.error || "Failed to start payment")

      if (data.authorization_url) {
        window.location.href = data.authorization_url
        return
      }

      throw new Error("No payment link was returned")
    } catch (error: any) {
      toast({
        title: "Payment Failed",
        description: error.message || "Could not start payment.",
        variant: "destructive",
      })
      setBuying(false)
    }
  }

  if (alreadyPurchased) {
    return (
      <Button asChild className="w-full bg-green-600 hover:bg-green-700 text-white py-6 text-lg">
        <Link href="/shop/orders">
          <CheckCircle className="mr-2 h-5 w-5" />
          You Own This — Access Content
        </Link>
      </Button>
    )
  }

  if (!isAuthenticated) {
    return (
      <Button asChild className="w-full bg-purple-600 hover:bg-purple-700 text-white py-6 text-lg">
        <Link href={`/login?next=${encodeURIComponent(`/shop/product/${productSlug || productId}`)}`}>
          <Lock className="mr-2 h-5 w-5" />
          Sign in to Buy
        </Link>
      </Button>
    )
  }

  return (
    <div className="space-y-3">
      <Dialog open={open} onOpenChange={setOpen}>
        <DialogTrigger asChild>
          <Button className="w-full bg-gradient-to-r from-purple-600 to-blue-600 hover:from-purple-700 hover:to-blue-700 text-white shadow-lg text-lg py-6">
            <ShoppingCart className="mr-2 h-5 w-5" />
            Buy Now — ₦{price.toLocaleString()}
          </Button>
        </DialogTrigger>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>Unlock this digital product</DialogTitle>
            <DialogDescription className="space-y-2 pt-1 text-sm">
              <span className="font-medium text-gray-900">{title}</span>
              <span className="block text-lg font-bold text-purple-700">₦{price.toLocaleString()}</span>
              <span className="block text-xs text-gray-500">
                Secure payment via Flutterwave or Paystack. Your access will be unlocked instantly
                after payment.
              </span>
            </DialogDescription>
          </DialogHeader>
          <DialogFooter className="gap-2">
            <Button variant="outline" onClick={() => setOpen(false)} disabled={buying}>
              Cancel
            </Button>
            <Button onClick={handleBuy} disabled={buying} className="bg-purple-600 hover:bg-purple-700">
              {buying ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Download className="mr-2 h-4 w-4" />}
              {buying ? "Redirecting..." : "Proceed to Payment"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
