"use client"

import { useState, useEffect } from "react"
import { Copy, Check } from "lucide-react"
import { cn } from "@/lib/utils"

interface CopyButtonProps {
  text: string
  label?: string
  size?: "sm" | "md"
  className?: string
}

export function CopyButton({ text, label, size = "sm", className }: CopyButtonProps) {
  const [copied, setCopied] = useState(false)

  // Clean up timeout on unmount
  useEffect(() => {
    let timeoutId: NodeJS.Timeout | undefined

    if (copied) {
      timeoutId = setTimeout(() => setCopied(false), 2000)
    }

    return () => {
      if (timeoutId) {
        clearTimeout(timeoutId)
      }
    }
  }, [copied])

  async function handleCopy(): Promise<void> {
    try {
      await navigator.clipboard.writeText(text)
      setCopied(true)
    } catch (err) {
      console.error("Failed to copy text:", err)
    }
  }

  return (
    <button
      type="button"
      onClick={handleCopy}
      className={cn(
        "inline-flex items-center justify-center gap-2",
        "text-gray-600 hover:text-blue-600 dark:text-gray-400 dark:hover:text-blue-400",
        "transition-colors duration-200",
        "focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-1 rounded-md",
        size === "sm" ? "p-1.5" : "px-3 py-2",
        className,
      )}
      aria-label={copied ? "Copied!" : `Copy ${label || "text"}`}
      title={copied ? "Copied!" : `Copy ${label || "text"}`}
    >
      {copied ? (
        <Check className={size === "sm" ? "h-4 w-4" : "h-5 w-5"} />
      ) : (
        <Copy className={size === "sm" ? "h-4 w-4" : "h-5 w-5"} />
      )}
      {size === "md" && <span className="text-sm font-medium">{copied ? "Copied!" : "Copy"}</span>}
    </button>
  )
}
