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

export interface CustomActionButtonProps<T = any> {
  row: T;
  id: string; // Unique identifier for the action
  icon: React.ReactNode; // Icon component to display
  onClick: (row: T, hookData?: any) => Promise<void> | void; // Handler function
  visible?: (row: T, hookData?: any) => boolean; // Show/hide based on row data
  disabled?: (row: T, hookData?: any) => boolean | { disabled: boolean; message?: string };
  loading?: (row: T, hookData?: any) => boolean;
  title?: string | ((row: T) => string); // Tooltip text or translation key
  className?: string; // Optional custom CSS class
  hookData?: any; // Hook data passed through for context
  idField?: string; // Field name for unique identifier (default: 'id')
}

export function CustomActionButton<T = any>({
  row,
  id,
  icon,
  onClick,
  visible,
  disabled,
  loading,
  title,
  className = '',
  hookData,
  idField: _idField = 'id' // Available for future use, kept for API consistency
}: CustomActionButtonProps<T>) {
  const { t } = useLanguage();
  const [internalLoading, setInternalLoading] = useState(false);
  const [showSuccessFeedback, setShowSuccessFeedback] = useState(false);
  const [showErrorFeedback, setShowErrorFeedback] = useState(false);

  // Check visibility - if not visible, don't render
  if (visible && !visible(row, hookData)) {
    return null;
  }

  // Extract disabled state and tooltip message
  const disabledResult = disabled ? disabled(row, hookData) : false;
  const isDisabled = typeof disabledResult === 'boolean' ? disabledResult : disabledResult?.disabled || false;
  const disabledMessage = typeof disabledResult === 'object' ? disabledResult?.message : undefined;

  // Check loading state
  const isLoadingFromProp = loading ? loading(row, hookData) : false;
  const isLoading = isLoadingFromProp || internalLoading;

  // Resolve title
  let buttonTitle = '';
  if (typeof title === 'function') {
    buttonTitle = title(row);
  } else if (typeof title === 'string') {
    buttonTitle = t(title, title); // Try to translate, fallback to original
  }

  // Determine the final tooltip
  const finalTitle = isDisabled && disabledMessage ? disabledMessage : buttonTitle;

  const handleClick = async (e: React.MouseEvent) => {
    e.stopPropagation();
    if (!isDisabled && !isLoading) {
      setInternalLoading(true);
      setShowErrorFeedback(false);
      setShowSuccessFeedback(false);
      try {
        await onClick(row, hookData);
        // Show brief success feedback
        setShowSuccessFeedback(true);
        setTimeout(() => setShowSuccessFeedback(false), 2000);
      } catch (error) {
        console.error(`CustomActionButton (${id}): Action failed:`, error);
        setShowErrorFeedback(true);
        setTimeout(() => setShowErrorFeedback(false), 3000);
      } finally {
        setInternalLoading(false);
      }
    }
  };

  // Determine icon to show based on state
  let displayIcon: React.ReactNode = icon;
  if (isLoading) {
    displayIcon = '⏳';
  } else if (showSuccessFeedback) {
    displayIcon = '✓';
  } else if (showErrorFeedback) {
    displayIcon = '✗';
  }

  return (
    <button
      onClick={handleClick}
      className={`${styles.actionButton} ${styles.custom} ${isLoading ? styles.loading : ''} ${isDisabled ? styles.disabled : ''} ${showSuccessFeedback ? styles.success : ''} ${showErrorFeedback ? styles.error : ''} ${className}`}
      title={finalTitle}
      disabled={isDisabled || isLoading}
      data-action-id={id}
    >
      <span className={styles.actionIcon}>
        {displayIcon}
      </span>
    </button>
  );
}

export default CustomActionButton;
