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

export interface ViewActionButtonProps<T = any> {
  row: T;
  onView: (row: T) => Promise<void> | void;
  disabled?: boolean | { disabled: boolean; message?: string };
  loading?: boolean;
  className?: string;
  title?: string;
  isViewing?: boolean;
  hookData?: any; // Contains all hook data including operations
  // Field mappings
  idField?: string; // Field name for the unique identifier
  nameField?: string; // Field name for display name
  typeField?: string; // Field name for type/mime type
  loadingStateName?: string; // Name of the loading state in hookData
}

export function ViewActionButton<T = any>({
  row,
  onView,
  disabled = false,
  loading = false,
  className = '',
  title,
  isViewing = false,
  hookData,
  idField = 'id',
  nameField = 'name',
  typeField = 'type',
  loadingStateName = 'previewingFiles'
}: ViewActionButtonProps<T>) {
  const { t } = useLanguage();
  const [internalLoading, setInternalLoading] = useState(false);
  const [isPopupOpen, setIsPopupOpen] = 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 && !isViewing && !internalLoading) {
      setInternalLoading(true);
      try {
        
        // Call the onView callback if provided
        if (onView) {
          await onView(row);
        }
        // Open the file preview
        setIsPopupOpen(true);
      } finally {
        setInternalLoading(false);
      }
    }
  };

  const buttonTitle = title || t('files.action.preview', 'Preview');
  // Use hookData viewing state if available, otherwise use passed isViewing
  const loadingState = hookData?.[loadingStateName];
  const actualIsViewing = loadingState?.has((row as any)[idField]) || isViewing;
  const isLoading = loading || actualIsViewing || internalLoading;

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

  // Check if this is a file (has mimeType) or a regular entity (show details)
  const mimeType = (row as any)[typeField];
  const isFile = mimeType && typeof mimeType === 'string' && mimeType.length > 0;

  // Format row data for display
  const formatValue = (value: any): string => {
    if (value === null || value === undefined) return '-';
    if (typeof value === 'object') return JSON.stringify(value, null, 2);
    return String(value);
  };

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

      {/* Content Preview Component for files */}
      {isFile && (
        <ContentPreview
          isOpen={isPopupOpen}
          onClose={() => setIsPopupOpen(false)}
          fileId={(row as any)[idField]}
          fileName={(row as any)[nameField] || 'Unknown Item'}
          mimeType={mimeType}
        />
      )}

      {/* Details Popup for non-file entities */}
      {!isFile && (
        <Popup
          isOpen={isPopupOpen}
          title={t('common.details', 'Details')}
          onClose={() => setIsPopupOpen(false)}
          size="large"
        >
          <div style={{ padding: '20px' }}>
            <h3 style={{ marginBottom: '20px', fontSize: '1.2rem', fontWeight: 'bold' }}>
              {(row as any)[nameField] || (row as any)[idField] || 'Details'}
            </h3>
            <div style={{ display: 'grid', gap: '15px' }}>
              {Object.entries(row as Record<string, any>)
                .filter(([key]) => !key.startsWith('_') && key !== 'id')
                .map(([key, value]) => (
                  <div key={key} style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
                    <strong style={{ fontSize: '0.9rem', color: 'var(--color-text-secondary, #666)' }}>
                      {key.charAt(0).toUpperCase() + key.slice(1).replace(/([A-Z])/g, ' $1')}
                    </strong>
                    <div style={{ 
                      padding: '8px 12px', 
                      backgroundColor: 'var(--color-background-secondary, #f5f5f5)', 
                      borderRadius: '4px',
                      fontSize: '0.95rem',
                      wordBreak: 'break-word',
                      whiteSpace: 'pre-wrap'
                    }}>
                      {formatValue(value)}
                    </div>
                  </div>
                ))}
            </div>
          </div>
        </Popup>
      )}
    </>
  );
}

export default ViewActionButton;
