"use client"

import { useCallback, useState } from "react"
import { Copy, Sparkles } from "lucide-react"

import { Button } from "@/components/ui/button"
import { cn } from "@/lib/utils"

interface CopyButtonProps {
  value: string
  onCopied?: () => void
}

export function CopyButton({ value, onCopied }: CopyButtonProps) {
  const [copied, setCopied] = useState(false)

  const handleCopy = useCallback(async () => {
    try {
      await navigator.clipboard.writeText(value)
      setCopied(true)
      onCopied?.()
      setTimeout(() => setCopied(false), 2000)
    } catch (error) {
      console.error("Falha ao copiar código", error)
    }
  }, [onCopied, value])

  return (
    <Button
      type="button"
      variant="outline"
      size="sm"
      onClick={handleCopy}
      className="relative overflow-hidden border border-dashed border-slate-300 bg-white px-3 py-2 text-sm font-semibold text-neutral-700 transition-all hover:border-slate-400 hover:bg-white active:scale-[0.97]"
    >
      <span className="pointer-events-none absolute inset-0 rounded-md bg-neutral-900/5 opacity-0 transition-opacity duration-100 ease-out active:opacity-100" />
      <span
        className={cn(
          "flex items-center gap-2 transition-all duration-200 ease-out",
          copied ? "text-emerald-600" : "text-neutral-700"
        )}
      >
        {copied ? <Sparkles className="size-3.5" /> : <Copy className="size-3.5" />}
        {copied ? "Copiado!" : "Copiar código"}
      </span>
      <span className="sr-only">Copiar código de provisionamento</span>
    </Button>
  )
}
