import type { ExpenseRow, ExpenseUserOption } from '../../api/types'

export const EXPENSE_CATEGORIES = ['Expense', 'Purchase', 'Reimbursement', 'Donation'] as const

export function expensePurchasedByValue(u: ExpenseUserOption): string {
  const name = `${String(u.firstname ?? '').trim()} ${String(u.lastname ?? '').trim()}`.trim()
  return `${u.id}|${name}`
}

export function formatMoney(amount: number | string | undefined | null): string {
  const n = typeof amount === 'string' ? parseFloat(amount) : Number(amount)
  if (Number.isNaN(n)) return '$0.00'
  return `$${n.toFixed(2)}`
}

export function vendorDisplay(row: ExpenseRow): string {
  const v = row.retailor ?? row.retailer ?? ''
  return String(v).trim() || 'N/A'
}

export function purchaseDateDisplay(row: ExpenseRow): string {
  const raw =
    row.date_of_purchase ??
    row.purchase_date ??
    row.purchased_at ??
    row.date_purchased ??
    row.created_at ??
    null
  return formatMdY(raw)
}

export function formatMdY(raw?: string | null): string {
  if (raw == null || String(raw).trim() === '') return '-'
  const s = String(raw)
  const iso = /^(\d{4})-(\d{2})-(\d{2})/.exec(s)
  if (iso) return `${iso[2]}-${iso[3]}-${iso[1]}`
  const d = new Date(s)
  return Number.isNaN(d.getTime()) ? s : `${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}-${d.getFullYear()}`
}

export function formatCreatedAt(raw?: string | null): string {
  if (raw == null || String(raw).trim() === '') return ''
  const s = String(raw)
  const m = /^(\d{4})-(\d{2})-(\d{2})[T\s](\d{2}):(\d{2})/.exec(s)
  if (m) return `${m[2]}-${m[3]}-${m[1]} ${m[4]}:${m[5]}`
  const d = new Date(s)
  if (Number.isNaN(d.getTime())) return s
  const mm = String(d.getMonth() + 1).padStart(2, '0')
  const dd = String(d.getDate()).padStart(2, '0')
  const hh = String(d.getHours()).padStart(2, '0')
  const min = String(d.getMinutes()).padStart(2, '0')
  return `${mm}-${dd}-${d.getFullYear()} ${hh}:${min}`
}

export function toDateInputValue(raw?: string | null): string {
  if (!raw) return ''
  const m = /^(\d{4}-\d{2}-\d{2})/.exec(String(raw))
  return m ? m[1] : ''
}

export function totalExpenseAmount(rows: ExpenseRow[]): number {
  return rows.reduce((sum, e) => {
    const n = typeof e.amount === 'string' ? parseFloat(e.amount) : Number(e.amount)
    return sum + (Number.isNaN(n) ? 0 : n)
  }, 0)
}
