import React from 'react'

import { AgeCategoryCount, AgeCategoryType } from '../FilterBarTypes'

type Props = {
  ageCategoryCounts: AgeCategoryCount
  ageCategories?: AgeCategoryType[]
  guestLabel: string
  guestsLabel: string
  guestsPlaceholder: string
}

type AccType = {
  total: number
  html: string[]
}

export const parseGuests = ({
  guestLabel,
  guestsLabel,
  guestsPlaceholder,
  ageCategoryCounts,
  ageCategories,
}: Props) => {
  const parsedData = Object.entries(ageCategoryCounts).reduce(
    (acc: AccType, [key, value]) => {
      const parts = key.split('-')
      if (parts.length < 2) return acc

      const ageCategoryId = parts[1]
      const ageCategory = ageCategories?.find((c) => c.id === ageCategoryId)

      if (ageCategory && value) {
        return {
          total: acc.total + value,
          html: [...acc.html, `${value}`],
        }
      }

      return acc
    },
    { total: 0, html: [] }
  )

  if (!parsedData.total) {
    return {
      content: guestsPlaceholder,
      data: parsedData,
    }
  }

  const breakdown =
    parsedData.html.length > 1 ? parsedData.html.join(' + ') : null

  return {
    content: (
      <>
        <span className="will-guest-count">{parsedData.total}</span>{' '}
        {parsedData.total > 1 ? guestsLabel : guestLabel}
        {breakdown && <> &nbsp; ( {breakdown} )</>}
      </>
    ),
    data: parsedData,
  }
}
