import { useState } from 'react';
import { Check, Copy } from 'lucide-react';
import { copyToClipboard } from 'helpers/clipboard';

// A read-only value with a copy button — addresses, invoices, txids, xpubs.
//
// Never used for anything secret. A mnemonic gets its own deliberately awkward treatment in
// SeedBackupDialog rather than a one-tap copy, because "copied to clipboard" is where seeds go to die.

type CopyFieldProps = {
  value: string;
  label?: string;
  /** Wrap rather than truncate — right for a bech32 address, wrong for a table cell. */
  wrap?: boolean;
  className?: string;
};

export const CopyField = ({ value, label, wrap = false, className = '' }: CopyFieldProps) => {
  const [copied, setCopied] = useState(false);

  const copy = async () => {
    if (!(await copyToClipboard(value))) return;
    setCopied(true);
    setTimeout(() => setCopied(false), 1_500);
  };

  return (
    <div className={className}>
      {label && (
        <div className="mb-1 text-[11px] font-medium uppercase tracking-wide text-muted-foreground">{label}</div>
      )}
      <div className="flex items-start gap-2 rounded-lg border border-border bg-muted/40 px-3 py-2">
        <code className={`min-w-0 flex-1 font-mono text-xs ${wrap ? 'break-all' : 'truncate'}`}>{value}</code>
        <button
          type="button"
          onClick={copy}
          aria-label={`Copy ${label ?? 'value'}`}
          className="shrink-0 text-muted-foreground transition-colors hover:text-foreground"
        >
          {copied ? <Check className="h-3.5 w-3.5 text-emerald-500" /> : <Copy className="h-3.5 w-3.5" />}
        </button>
      </div>
    </div>
  );
};
