"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { ShoppingCart, CheckCircle, Loader2 } from "lucide-react"
import { useCart } from "@/lib/cart/context"
import { toast } from "sonner"
import type { Product } from "@/lib/products/types"

interface AddToCartButtonProps {
  product: Product
}

export function AddToCartButton({ product }: AddToCartButtonProps) {
  const { addItem } = useCart()
  const [isAdding, setIsAdding] = useState(false)
  const [isAdded, setIsAdded] = useState(false)

  const handleAddToCart = () => {
    if (isAdding || isAdded) return

    setIsAdding(true)
    setIsAdded(false)

    try {
      addItem({
        id: product.id,
        name: product.name,
        price: product.price,
        priceId: product.priceId!,
        image: product.images?.[0] || "/placeholder.svg",
        quantity: 1,
      })

      // Show success feedback
      setIsAdded(true)
      toast.success(`${product.name} added to cart!`)

      // Reset states after showing feedback
      setTimeout(() => {
        setIsAdding(false)
        setIsAdded(false)
      }, 2000)
    } catch (error) {
      console.error("Error adding to cart:", error)
      toast.error("Failed to add item to cart")
      setIsAdding(false)
    }
  }

  if (!product.priceId) {
    return (
      <Button disabled className="w-full">
        <span className="flex items-center gap-2">
          <span>Product unavailable</span>
        </span>
      </Button>
    )
  }

  return (
    <Button
      onClick={handleAddToCart}
      disabled={isAdding || isAdded}
      variant="brand"
      className="w-full h-12"
      size="lg"
    >
      <div className="flex items-center gap-2">
        {isAdding ? (
          <Loader2 className="h-4 w-4 animate-spin" />
        ) : isAdded ? (
          <CheckCircle className="h-4 w-4 text-green-500" />
        ) : (
          <ShoppingCart className="h-4 w-4" />
        )}
        <span>
          {isAdding ? "Adding..." : isAdded ? "Added!" : "Add to Cart"}
        </span>
      </div>
    </Button>
  )
}
