/**
 * Format ISO date string to readable format
 * @param dateString - ISO date string (e.g., "2025-10-31T12:02:50.394Z")
 * @param options - Optional format options
 * @returns Formatted date string (e.g., "Nov 3, 2025, 8:57 AM")
 */
export function formatDateTime(dateString: string | Date | null | undefined, options?: {
  includeTime?: boolean;
  includeSeconds?: boolean;
  format?: 'short' | 'medium' | 'long';
}): string {
  if (!dateString) return 'N/A';
  
  try {
    const date = typeof dateString === 'string' ? new Date(dateString) : dateString;
    
    if (isNaN(date.getTime())) {
      return 'Invalid Date';
    }

    const { 
      includeTime = true, 
      includeSeconds = false, 
      format = 'medium' 
    } = options || {};

    if (!includeTime) {
      // Date only
      return date.toLocaleDateString('en-US', {
        year: 'numeric',
        month: format === 'short' ? 'short' : 'long',
        day: 'numeric'
      });
    }

    // Date with time
    return date.toLocaleString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: 'numeric',
      minute: '2-digit',
      ...(includeSeconds && { second: '2-digit' }),
      hour12: true
    });
  } catch (error) {
    console.error('Error formatting date:', error);
    return String(dateString);
  }
}

/**
 * Format date to relative time (e.g., "2 hours ago", "3 days ago")
 */
export function formatRelativeTime(dateString: string | Date | null | undefined): string {
  if (!dateString) return 'N/A';
  
  try {
    const date = typeof dateString === 'string' ? new Date(dateString) : dateString;
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffSec = Math.floor(diffMs / 1000);
    const diffMin = Math.floor(diffSec / 60);
    const diffHour = Math.floor(diffMin / 60);
    const diffDay = Math.floor(diffHour / 24);

    if (diffSec < 60) return 'just now';
    if (diffMin < 60) return `${diffMin} minute${diffMin > 1 ? 's' : ''} ago`;
    if (diffHour < 24) return `${diffHour} hour${diffHour > 1 ? 's' : ''} ago`;
    if (diffDay < 7) return `${diffDay} day${diffDay > 1 ? 's' : ''} ago`;
    
    // For older dates, show formatted date
    return formatDateTime(dateString, { includeTime: false });
  } catch (error) {
    return String(dateString);
  }
}

/**
 * Format date to short format (e.g., "Oct 31, 2025")
 */
export function formatDateShort(dateString: string | Date | null | undefined): string {
  return formatDateTime(dateString, { includeTime: false, format: 'short' });
}

/**
 * Format time only (e.g., "8:57 AM")
 */
export function formatTimeOnly(dateString: string | Date | null | undefined): string {
  if (!dateString) return 'N/A';
  
  try {
    const date = typeof dateString === 'string' ? new Date(dateString) : dateString;
    
    return date.toLocaleTimeString('en-US', {
      hour: 'numeric',
      minute: '2-digit',
      hour12: true
    });
  } catch (error) {
    return String(dateString);
  }
}

/**
 * Format date with day first, then month (mmm), then year (e.g., "15 Nov 2025, 3:47:28 PM")
 * Format: dd mmm yyyy (day first, then month name, then year)
 * @param dateString - ISO date string or Date object
 * @param includeTime - Whether to include time in the format
 * @returns Formatted date string with day first
 */
export function formatDateDDMMYYYY(dateString: string | Date | null | undefined, includeTime: boolean = false): string {
  if (!dateString) return 'N/A';
  
  try {
    const date = typeof dateString === 'string' ? new Date(dateString) : dateString;
    
    if (isNaN(date.getTime())) {
      return 'Invalid Date';
    }

    // Always put day first, then month (mmm format), then year
    const day = String(date.getDate()).padStart(2, '0');
    const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    const month = monthNames[date.getMonth()]; // Use month name (mmm)
    const year = date.getFullYear();

    if (includeTime) {
      const hours24 = date.getHours();
      const hours12 = hours24 % 12 || 12;
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      const ampm = hours24 >= 12 ? 'PM' : 'AM';
      // Format: dd mmm yyyy, hh:mm:ss AM/PM (day first, then month, then year)
      return `${day} ${month} ${year}, ${hours12}:${minutes}:${seconds} ${ampm}`;
    }

    // Format: dd mmm yyyy (day first, then month, then year)
    return `${day} ${month} ${year}`;
  } catch (error) {
    console.error('Error formatting date:', error);
    return String(dateString);
  }
}

