import * as React from 'react'
import { Check, Copy } from 'lucide-react'
import { Button } from './Button'
import { cn } from '@/lib/utils'

interface CopyButtonProps
  extends Omit<React.ComponentProps<typeof Button>, 'variant' | 'size' | 'children'> {
  text: string
  displayText?: string
  successDuration?: number
}

const CopyButton = React.forwardRef<HTMLButtonElement, CopyButtonProps>(
  (
    { className, text, displayText, successDuration = 2000, ...props },
    ref
  ) => {
    const [copied, setCopied] = React.useState(false)

    const handleCopy = React.useCallback(async () => {
      try {
        await navigator.clipboard.writeText(text)
        setCopied(true)
        setTimeout(() => setCopied(false), successDuration)
      } catch {
      }
    }, [text, successDuration])

    return (
      <Button
        ref={ref}
        variant="ghost"
        size="sm"
        onClick={handleCopy}
        className={cn('gap-1.5 text-fg-muted hover:text-fg', className)}
        {...props}
      >
        {copied ? (
          <>
            <Check className="h-3.5 w-3.5 text-emerald-400" />
            <span className="text-emerald-400">Copied</span>
          </>
        ) : (
          <>
            <Copy className="h-3.5 w-3.5" />
            <span>{displayText ?? 'Copy'}</span>
          </>
        )}
      </Button>
    )
  }
)
CopyButton.displayName = 'CopyButton'

export { CopyButton }
