import { format, formatDistanceToNow, isToday, isYesterday } from 'date-fns'
import { he, enUS } from 'date-fns/locale'
import { t, isRtl } from '@/lib/i18n'

function getDateLocale() {
  return isRtl() ? he : enUS
}

/**
 * Format date for display
 */
export function formatDate(date: string | Date): string {
  // MySQL 'YYYY-MM-DD HH:MM:SS' fails to parse in Safari; normalize to ISO, then guard
  // against Invalid Date (date-fns throws on an invalid date).
  const d = typeof date === 'string' ? new Date(date.replace(' ', 'T')) : date
  if (isNaN(d.getTime())) return '-'

  if (isToday(d)) {
    return `${t('Today')}, ${format(d, 'HH:mm')}`
  }
  
  if (isYesterday(d)) {
    return `${t('Yesterday')}, ${format(d, 'HH:mm')}`
  }
  
  return format(d, 'dd/MM/yyyy HH:mm')
}

/**
 * Format relative time
 */
export function formatRelativeTime(date: string | Date): string {
  const d = typeof date === 'string' ? new Date(date.replace(' ', 'T')) : date
  if (isNaN(d.getTime())) return '-'
  return formatDistanceToNow(d, { addSuffix: true, locale: getDateLocale() })
}

/**
 * Format number with comma separators
 */
export function formatNumber(num: number): string {
  return num.toLocaleString(isRtl() ? 'he-IL' : 'en-US')
}

/**
 * Format percentage
 */
export function formatPercentage(num: number, decimals = 0): string {
  return `${num.toFixed(decimals)}%`
}

/**
 * Format phone number (Israeli format)
 */
export function formatPhone(phone: string | null): string {
  if (!phone) return '-'
  
  // Remove non-digits
  const digits = phone.replace(/\D/g, '')
  
  // Format as 05X-XXX-XXXX
  if (digits.length === 10 && digits.startsWith('05')) {
    return `${digits.slice(0, 3)}-${digits.slice(3, 6)}-${digits.slice(6)}`
  }
  
  return phone
}

/**
 * Format credit values for display — always 1 decimal place.
 * Used everywhere credits are shown (Knowledge Base, Usage Dashboard, etc.)
 */
export function formatCredits(value: number | null | undefined): string {
  if (value == null) return '—'
  const rounded = Math.round(value * 10) / 10
  return rounded.toLocaleString(isRtl() ? 'he-IL' : 'en-US', {
    minimumFractionDigits: 1,
    maximumFractionDigits: 1,
  })
}

/**
 * Truncate text with ellipsis
 */
export function truncate(text: string, maxLength: number): string {
  if (text.length <= maxLength) return text
  return text.slice(0, maxLength) + '...'
}










