import type { FC } from 'react'
import { useLayoutEffect, useState } from 'react'
import type { StyledTagProps } from '../StyledTag'
import StyledTag from '../StyledTag'

const RERENDER_INTERVAL_SECONDS = 10

export const timedFormatter = (datetime: Date, minimal?: boolean) => {
  const secs = (Date.now() - datetime.getTime()) / 1000
  if (secs < 10) {
    return 'Just now'
  }
  if (secs < 60) {
    return minimal ? '<1m ago' : 'Less than a minute ago'
  }
  const hours = Math.floor(secs / 3600)
  const minutes = Math.floor(secs / 60) % 60
  const hourString = minimal
    ? `${hours}h`
    : `${hours} ${hours > 1 ? 'hours' : 'hour'}`
  const minuteString = minimal
    ? `${minutes}m`
    : `${minutes % 60} ${minutes % 60 > 1 ? 'minutes' : 'minute'}`

  return `${hours > 0 ? `${hourString} ` : ''}${minutes > 0 ? minuteString : ''} ago`
}

type TimestampProps = Omit<StyledTagProps, 'content'> & {
  datetime: Date
  minimal?: boolean
}

const Timestamp: FC<TimestampProps> = ({ datetime, minimal, ...props }) => {
  const [time, setTime] = useState<string>('')
  useLayoutEffect(() => {
    if (datetime === undefined) return

    setTime(timedFormatter(datetime, minimal))
    const interval = setInterval(() => {
      setTime(timedFormatter(datetime, minimal))
    }, RERENDER_INTERVAL_SECONDS * 1000)
    return () => {
      clearInterval(interval)
    }
  }, [datetime, minimal])

  return <StyledTag content={time} {...props} />
}

export default Timestamp
