import React, { useMemo } from 'react'


const timeOnlyFormatter = new Intl.DateTimeFormat('en-US', {
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric'
})

const dateAndTimeFormatter = new Intl.DateTimeFormat('en-US', {
  month: 'short',
  day: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric',
  hour12: false
})

export type TimestampProps = {
  children: Date | string
  options?: Intl.DateTimeFormatOptions
}

export const Timestamp = React.memo<TimestampProps>(({ children: value, options }) => {
  const dateValue = useMemo(() => (typeof value === 'string' ? new Date(value) : value), [value])

  const fmt = useMemo(() => {
    if (options) {
      return new Intl.DateTimeFormat('en-US', options).format(dateValue)
    }

    if (dateValue.toDateString() === new Date().toDateString()) {
      return timeOnlyFormatter.format(dateValue)
    }

    return dateAndTimeFormatter.format(dateValue)
  }, [options, dateValue])

  return <time dateTime={dateValue.toISOString()}>{fmt}</time>
})
