import type { FamilyGuardianRow, FamilyRow, FamilyStudentRow } from '../../api/types'

export function normalize(s: string): string {
  return s.trim().toLowerCase()
}

export function relationLabel(relRaw: string | null | undefined): string {
  const rel = String(relRaw ?? '').toLowerCase().trim()
  if (rel === 'guardian') return 'second parent'
  if (rel === 'primary') return 'first parent'
  return String(relRaw ?? '').trim()
}

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

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 financeSummary(f: FamilyRow): {
  invoices_count: number
  total_amount: number
  paid_amount: number
  balance: number
} {
  const s = (f as Record<string, unknown>).finance_summary as Record<string, unknown> | undefined
  return {
    invoices_count: Number(s?.invoices_count ?? 0),
    total_amount: Number(s?.total_amount ?? 0),
    paid_amount: Number(s?.paid_amount ?? 0),
    balance: Number(s?.balance ?? 0),
  }
}

/** Mirrors PHP `index.php` search blob for client-side filtering. */
/** Client filter matching CI `applyFilter()` (card + inner text). */
export function familyCardMatches(f: FamilyRow, qRaw: string): boolean {
  const q = normalize(qRaw.trim())
  if (!q) return true
  if (normalize(familySearchBlob(f)).includes(q)) return true
  for (const g of f.guardians ?? []) {
    const row = [
      g.firstname,
      g.lastname,
      g.email,
      g.cellphone,
      g.relation,
      g.address_street,
      g.city,
      g.state,
      g.zip,
    ]
      .map((x) => String(x ?? ''))
      .join(' ')
    if (normalize(row).includes(q)) return true
  }
  for (const s of f.students ?? []) {
    const gr = (s as FamilyStudentRow & { grade?: string }).grade
    const row = [s.firstname, s.lastname, gr].map((x) => String(x ?? '')).join(' ')
    if (normalize(row).includes(q)) return true
  }
  return false
}

export function familySearchBlob(f: FamilyRow): string {
  const parts: string[] = []
  const push = (x: unknown) => {
    const t = String(x ?? '').trim()
    if (t) parts.push(t)
  }
  push(f.household_name)
  push(f.family_code)
  push(f.primary_phone)
  push(f.preferred_lang)
  push(f.preferred_contact_method)
  push(f.address_line1)
  push(f.address_line2)
  push(f.city)
  push(f.state)
  push(f.postal_code)
  push(f.country)
  for (const gg of f.guardians ?? []) {
    push(`${gg.firstname ?? ''} ${gg.lastname ?? ''}`.trim())
    push(gg.email)
    push(gg.cellphone)
    push(gg.relation)
    push(gg.address_street)
    push(gg.city)
    push(gg.state)
    push(gg.zip)
  }
  for (const ss of f.students ?? []) {
    push(`${ss.firstname ?? ''} ${ss.lastname ?? ''}`.trim())
    push((ss as FamilyStudentRow & { grade?: string }).grade)
  }
  return normalize(parts.join(' '))
}

export function cardTitle(f: FamilyRow): string {
  const raw = String(f.household_name ?? '').trim()
  if (raw && !/^\s*Family\s+of\s+User\s*\d+\s*$/i.test(raw)) return raw
  const guardians = f.guardians ?? []
  const primary = guardians.find((g) => g.is_primary) ?? guardians[0]
  const ln = String(primary?.lastname ?? '').trim()
  if (ln) return `Family of ${ln}`
  return 'Family'
}

export function guardianAddress(g: FamilyGuardianRow): string {
  const addrParts = [
    g.address_street ?? '',
    `${String(g.city ?? '').trim()} ${String(g.state ?? '').trim()}`.trim(),
    g.zip ?? '',
  ].filter((x) => String(x).trim() !== '')
  return addrParts.length > 0 ? addrParts.join(', ') : '—'
}
