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

export interface DownloadActionButtonProps<T = any> {
  row: T;
  onDownload: (row: T) => Promise<void> | void;
  disabled?: boolean | { disabled: boolean; message?: string };
  loading?: boolean;
  className?: string;
  title?: string;
  hookData?: any;
  idField?: string;
  loadingStateName?: string;
}

export function DownloadActionButton<T = any>({
  row,
  onDownload,
  disabled = false,
  loading = false,
  className = '',
  title,
  hookData,
  idField = 'id',
  loadingStateName = 'downloadingFiles'
}: DownloadActionButtonProps<T>) {
  const { t } = useLanguage();
  const [internalLoading, setInternalLoading] = 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 && !internalLoading) {
      setInternalLoading(true);
      try {
        if (onDownload) {
          await onDownload(row);
        }
      } finally {
        setInternalLoading(false);
      }
    }
  };

  const buttonTitle = title || t('files.action.download', 'Download');
  // Use hookData loading state if available
  const loadingState = hookData?.[loadingStateName];
  const actualIsLoading = loadingState?.has((row as any)[idField]) || loading || internalLoading;

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

  return (
    <button
      onClick={handleClick}
      className={`${styles.actionButton} ${styles.download} ${actualIsLoading ? styles.loading : ''} ${isDisabled ? styles.disabled : ''} ${className}`}
      title={finalTitle}
      disabled={isDisabled || actualIsLoading}
    >
      <span className={styles.actionIcon}>
        {actualIsLoading ? '⏳' : <IoIosDownload />}
      </span>
    </button>
  );
}

export default DownloadActionButton;
