import React, { useState } from 'react';
import { useLanguage } from '../../../providers/language/LanguageContext';
import styles from './CopyableTruncatedValue.module.css';

export interface CopyableTruncatedValueProps {
  value: string;
  maxLength?: number;
  className?: string;
  onClick?: (e: React.MouseEvent) => void;
}

export function CopyableTruncatedValue({ 
  value, 
  maxLength = 20,
  className = '',
  onClick
}: CopyableTruncatedValueProps) {
  const { t } = useLanguage();
  const [copied, setCopied] = useState(false);
  const [showFull, setShowFull] = useState(false);

  // Determine if value should be truncated
  const shouldTruncate = value.length > maxLength;
  const displayValue = shouldTruncate && !showFull 
    ? `${value.substring(0, maxLength)}...` 
    : value;

  const handleClick = async (e: React.MouseEvent) => {
    e.stopPropagation(); // Prevent row click or other parent handlers
    
    // Call custom onClick handler if provided
    if (onClick) {
      onClick(e);
    }
    
    try {
      await navigator.clipboard.writeText(value);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (error) {
      console.error('Failed to copy to clipboard:', error);
    }
  };

  const handleDoubleClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    if (shouldTruncate) {
      setShowFull(!showFull);
    }
  };

  const tooltipText = copied 
    ? t('common.copied', 'Copied!') 
    : `${t('common.copy', 'copy')}: ${value}`;

  return (
    <span 
      className={`${styles.copyableValue} ${className}`}
      onClick={handleClick}
      onDoubleClick={handleDoubleClick}
      title={tooltipText}
    >
      <span className={styles.truncatedText}>{displayValue}</span>
      {copied && <span className={styles.copiedIndicator}>✓</span>}
    </span>
  );
}

export default CopyableTruncatedValue;

