import { useState } from "react"
import { Check, Copy } from "lucide-react"

/**
 * A monospace id (UUID, slug, token name) that copies to the clipboard on
 * click, with a brief checkmark. Raw ids are common in an admin console and
 * useless if you can't get them into a support ticket or a CLI.
 */
export function CopyId({
  value,
  label,
  className = "",
  dataAction,
}: {
  value: string
  /** What's being copied, for the aria-label. Defaults to "id". */
  label?: string
  className?: string
  dataAction?: string
}) {
  const [copied, setCopied] = useState(false)

  const copy = async () => {
    try {
      await navigator.clipboard.writeText(value)
      setCopied(true)
      setTimeout(() => setCopied(false), 1200)
    } catch {
      // Clipboard blocked (insecure context / permissions) — no-op; the value
      // is still selectable by hand.
    }
  }

  return (
    <button
      type="button"
      onClick={copy}
      data-action={dataAction}
      aria-label={`Copy ${label ?? "id"}`}
      title="Copy"
      className={`group inline-flex max-w-full items-center gap-1 rounded bg-muted px-1.5 py-0.5 font-mono text-xs transition-colors hover:bg-accent ${className}`}
    >
      <span className="truncate">{value}</span>
      {copied ? (
        <Check className="size-3 shrink-0 text-emerald-500" />
      ) : (
        <Copy className="size-3 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100" />
      )}
    </button>
  )
}
