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

interface CopyButtonProps {
  text: string;
  itemKey: string;
}

export const CopyButton = ({ text }: CopyButtonProps) => {
  const [isCopied, setIsCopied] = useState(false);
  const canCopy = text && text !== 'N/A';
  
  const copyToClipboard = () => {
    if (!canCopy) return;
    
    navigator.clipboard.writeText(text)
      .then(() => {
        // Show success state
        setIsCopied(true);
        
        // Show toast notification
        toast.success(`Copied: ${text}`);
        
        // Reset after 2 seconds
        setTimeout(() => {
          setIsCopied(false);
        }, 2000);
      })
      .catch(err => {
        console.error('Failed to copy:', err);
        toast.error('Failed to copy to clipboard');
      });
  };
  
  return (
    <button
      onClick={(e) => {
        e.preventDefault();
        e.stopPropagation();
        copyToClipboard();
      }}
      className={`ml-1 inline-flex items-center justify-center rounded-full p-1 transition-colors ${
        canCopy 
          ? isCopied 
            ? "bg-green-100 text-green-600 hover:bg-green-200 dark:bg-green-900/30 dark:text-green-400" 
            : "text-muted-foreground hover:bg-gray-100 dark:hover:bg-gray-800" 
          : "opacity-50 cursor-not-allowed"
      }`}
      disabled={!canCopy}
      title={canCopy ? "Copy to clipboard" : "Nothing to copy"}
    >
      {isCopied ? (
        <Check className="h-3 w-3" />
      ) : (
        <Copy className="h-3 w-3" />
      )}
    </button>
  );
}; 