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;
  isDownloading?: boolean;
  hookData?: any; // Contains all hook data including operations
  // Field mappings
  idField?: string; // Field name for the unique identifier
  loadingStateName?: string; // Name of the loading state in hookData
  operationName?: string; // Name of the operation function in hookData
}

export function DownloadActionButton<T = any>({
  row,
  onDownload,
  disabled = false,
  loading = false,
  className = '',
  title,
  isDownloading = false,
  hookData,
  idField = 'id',
  loadingStateName = 'downloadingFiles',
  operationName
}: 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 && !isDownloading && !internalLoading) {
      setInternalLoading(true);
      try {
        // If operationName is provided and hookData is available, use the hook function
        if (operationName && hookData && hookData[operationName]) {
          await hookData[operationName]((row as any)[idField], (row as any).file_name);
        } else if (onDownload) {
          // Fallback to the provided onDownload function
          await onDownload(row);
        } else {
          console.error('No download function available');
        }
      } finally {
        setInternalLoading(false);
      }
    }
  };

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

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

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

export default DownloadActionButton;
