/**
 * Utility functions for message formatting and styling
 */

/**
 * Formats a timestamp to a readable date/time string
 * Handles both Unix timestamps in seconds and milliseconds
 * Formats exactly like FormGenerator component
 */
export const formatTimestamp = (timestamp?: number): string => {
  if (!timestamp) return '';
  
  try {
    // Backend sends UTC timestamp in seconds (Unix timestamp)
    // JavaScript Date constructor expects milliseconds
    // Check if timestamp is in seconds (typical Unix timestamp range)
    // Timestamps less than 10000000000 (year 2286) are likely in seconds
    let date: Date;
    if (timestamp < 10000000000) {
      // Convert seconds to milliseconds
      date = new Date(timestamp * 1000);
    } else {
      // Already in milliseconds
      date = new Date(timestamp);
    }
    
    // Validate date
    if (isNaN(date.getTime())) {
      console.warn('Invalid timestamp:', timestamp);
      return '';
    }
    
    // Format exactly like FormGenerator: YYYY-MM-DD HH:MM:SS GMT±HHMM
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    const timezoneOffset = date.getTimezoneOffset();
    const offsetHours = Math.floor(Math.abs(timezoneOffset) / 60);
    const offsetMinutes = Math.abs(timezoneOffset) % 60;
    const offsetSign = timezoneOffset <= 0 ? '+' : '-';
    const timezone = `GMT${offsetSign}${String(offsetHours).padStart(2, '0')}${offsetMinutes > 0 ? ':' + String(offsetMinutes).padStart(2, '0') : ''}`;
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds} ${timezone}`;
  } catch (error) {
    console.warn('Error formatting timestamp:', timestamp, error);
    return '';
  }
};

/**
 * Formats file size to human-readable format
 */
export const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
};

/**
 * Gets status badge color class based on status
 */
export const getStatusClass = (baseStyles: any, status?: string, success?: boolean): string => {
  if (success === false) return baseStyles.statusError;
  if (success === true) return baseStyles.statusSuccess;
  
  switch (status?.toLowerCase()) {
    case 'completed':
    case 'success':
      return baseStyles.statusSuccess;
    case 'failed':
    case 'error':
      return baseStyles.statusError;
    case 'running':
    case 'pending':
      return baseStyles.statusPending;
    default:
      return baseStyles.statusDefault;
  }
};

