import React, { useState } from 'react';
import { IoCopy } from 'react-icons/io5';
import { useLanguage } from '../../../../providers/language/LanguageContext';
import styles from '../ActionButton.module.css';

export interface CopyActionButtonProps<T = any> {
  row: T;
  onCopy?: (row: T) => Promise<void> | void;
  disabled?: boolean | { disabled: boolean; message?: string };
  loading?: boolean;
  className?: string;
  title?: string;
  isCopying?: boolean;
  // Field mappings for clipboard copy
  contentField?: string; // Field name for content to copy to clipboard (default: 'content')
}

export function CopyActionButton<T = any>({
  row,
  onCopy,
  disabled = false,
  loading = false,
  className = '',
  title,
  isCopying = false,
  contentField = 'content'
}: CopyActionButtonProps<T>) {
  const { t } = useLanguage();
  const [internalLoading, setInternalLoading] = useState(false);
  const [showCopiedFeedback, setShowCopiedFeedback] = useState(false);
  
  // Extract disabled state and tooltip message
  const isDisabled = typeof disabled === 'boolean' ? disabled : disabled?.disabled || false;
  const disabledMessage = typeof disabled === 'object' ? disabled?.message : undefined;

  const handleClick = async (e: React.MouseEvent) => {
    e.stopPropagation();
    if (!isDisabled && !loading && !isCopying && !internalLoading) {
      setInternalLoading(true);
      try {
        if (onCopy) {
          // Use custom copy function if provided
          await onCopy(row);
        } else {
          // Default behavior: copy the specified field content to clipboard
          const contentToCopy = (row as any)[contentField];
          
          if (contentToCopy !== undefined && contentToCopy !== null) {
            await navigator.clipboard.writeText(String(contentToCopy));
          } else {
            console.warn(`Field "${contentField}" not found or is empty in row:`, row);
          }
        }
        
        // Show copied feedback
        setShowCopiedFeedback(true);
        setTimeout(() => setShowCopiedFeedback(false), 2000);
      } catch (error) {
        console.error('Copy to clipboard failed:', error);
      } finally {
        setInternalLoading(false);
      }
    }
  };

  const buttonTitle = title || t('prompts.action.copy', 'Copy to Clipboard');
  const isLoading = loading || isCopying || internalLoading;

  // Determine the final button title (tooltip)
  const finalTitle = isDisabled && disabledMessage ? disabledMessage : buttonTitle;

  return (
    <button
      onClick={handleClick}
      className={`${styles.actionButton} ${styles.copy} ${isLoading ? styles.loading : ''} ${isDisabled ? styles.disabled : ''} ${className}`}
      title={finalTitle}
      disabled={isDisabled || isLoading}
    >
      <span className={styles.actionIcon}>
        {showCopiedFeedback ? '✓' : isLoading ? '⏳' : <IoCopy />}
      </span>
    </button>
  );
}

export default CopyActionButton;

