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

interface CopyableFieldProps {
  value: string;
  label: string;
  variant?: "input" | "inline";
}

export function CopyableField({ value, label, variant = "input" }: CopyableFieldProps) {
  const [copied, setCopied] = useState(false);

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(value);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      console.error("Failed to copy:", err);
    }
  };

  if (variant === "inline") {
    return (
      <div className="flex items-center gap-2 group">
        <span className="text-xs text-zinc-500">{label}:</span>
        <span className="font-mono text-xs text-zinc-600 break-all">
          {value}
        </span>
        <button
          type="button"
          onClick={handleCopy}
          className="p-1 text-zinc-400 hover:text-zinc-300 transition-colors rounded hover:bg-zinc-700/50 flex-shrink-0 opacity-0 group-hover:opacity-100"
          title="Copy to clipboard"
        >
          {copied ? (
            <Check size={14} className="text-green-400" />
          ) : (
            <Copy size={14} />
          )}
        </button>
      </div>
    );
  }

  return (
    <div>
      <label className="text-xs text-zinc-500 block mb-1">
        {label}
      </label>
      <div className="relative">
        <div className="bg-zinc-800/50 border border-zinc-700 rounded px-3 py-2 pr-10 font-mono text-sm text-zinc-300 break-all">
          {value}
        </div>
        <button
          type="button"
          onClick={handleCopy}
          className="absolute right-2 top-1/2 -translate-y-1/2 p-1.5 text-zinc-400 hover:text-zinc-300 transition-colors rounded hover:bg-zinc-700/50"
          title="Copy to clipboard"
        >
          {copied ? (
            <Check size={16} className="text-green-400" />
          ) : (
            <Copy size={16} />
          )}
        </button>
      </div>
    </div>
  );
}
