/**
 * Formatting utilities
 */

import { format, formatDistance, formatDistanceToNow } from 'date-fns';

/**
 * Format currency
 * @param {number} amount
 * @param {string} currency
 * @returns {string}
 */
export const formatCurrency = (amount, currency = 'KES') => {
  if (amount === null || amount === undefined) return '0.00';
  return new Intl.NumberFormat('en-KE', {
    style: 'currency',
    currency: currency,
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  }).format(amount);
};

/**
 * Format number
 * @param {number} number
 * @param {number} decimals
 * @returns {string}
 */
export const formatNumber = (number, decimals = 2) => {
  if (number === null || number === undefined) return '0';
  return new Intl.NumberFormat('en-KE', {
    minimumFractionDigits: decimals,
    maximumFractionDigits: decimals,
  }).format(number);
};

/**
 * Format date
 * @param {Date|string} date
 * @param {string} formatString
 * @returns {string}
 */
export const formatDate = (date, formatString = 'dd MMM yyyy') => {
  if (!date) return '';
  try {
    return format(new Date(date), formatString);
  } catch (error) {
    return '';
  }
};

/**
 * Format datetime
 * @param {Date|string} date
 * @returns {string}
 */
export const formatDateTime = (date) => {
  return formatDate(date, 'dd MMM yyyy, HH:mm');
};

/**
 * Format relative time
 * @param {Date|string} date
 * @returns {string}
 */
export const formatRelativeTime = (date) => {
  if (!date) return '';
  try {
    return formatDistanceToNow(new Date(date), { addSuffix: true });
  } catch (error) {
    return '';
  }
};

/**
 * Format percentage
 * @param {number} value
 * @param {number} decimals
 * @returns {string}
 */
export const formatPercentage = (value, decimals = 2) => {
  if (value === null || value === undefined) return '0%';
  return `${parseFloat(value).toFixed(decimals)}%`;
};

/**
 * Format phone number
 * @param {string} phone
 * @returns {string}
 */
export const formatPhone = (phone) => {
  if (!phone) return '';
  // Remove non-numeric characters
  const cleaned = phone.replace(/\D/g, '');
  // Format as +254 XXX XXX XXX
  if (cleaned.length === 12 && cleaned.startsWith('254')) {
    return `+${cleaned.slice(0, 3)} ${cleaned.slice(3, 6)} ${cleaned.slice(6, 9)} ${cleaned.slice(9)}`;
  }
  // Format as 0XXX XXX XXX
  if (cleaned.length === 10 && cleaned.startsWith('0')) {
    return `${cleaned.slice(0, 4)} ${cleaned.slice(4, 7)} ${cleaned.slice(7)}`;
  }
  return phone;
};

