// PrinterSelect.js
import { useState, useEffect } from 'react'
import PropTypes from 'prop-types'
import { Flex, Typography, Tag } from 'antd'
import moment from 'moment'

const { Text } = Typography

const formatTimeDifference = (dateTime) => {
  const now = moment()
  const diff = moment(dateTime)
  const duration = moment.duration(now.diff(diff))

  const years = Math.floor(duration.asYears())
  const months = Math.floor(duration.asMonths()) % 12
  const weeks = Math.floor(duration.asWeeks()) % 4
  const days = Math.floor(duration.asDays()) % 7
  const hours = duration.hours()
  const minutes = duration.minutes()
  const seconds = duration.seconds()

  if (years > 0) {
    return `${years}y`
  } else if (months > 0) {
    return `${months}mo`
  } else if (weeks > 0) {
    return `${weeks}w`
  } else if (days > 0) {
    return `${days}d`
  } else if (hours > 0) {
    return `${hours}h`
  } else if (minutes > 0) {
    return `${minutes}m`
  } else {
    return `${seconds}s`
  }
}

const TimeDisplay = ({
  dateTime,
  showDate = true,
  showTime = true,
  showSince = false,
  type = 'primary'
}) => {
  const [timeAgo, setTimeAgo] = useState(formatTimeDifference(dateTime))

  useEffect(() => {
    if (showSince) {
      const timer = setInterval(() => {
        setTimeAgo(formatTimeDifference(dateTime))
      }, 1000)

      return () => clearInterval(timer)
    }
  }, [dateTime, showSince])

  if (!dateTime) {
    return <Text type='secondary'>n/a</Text>
  }

  var dateFormat = ''
  if (showDate == true) {
    dateFormat += 'YYYY-MM-DD '
  }
  if (showTime == true) {
    dateFormat += 'HH:mm:ss '
  }

  const formattedDate = moment(dateTime).format(dateFormat)

  return (
    <Flex align={'center'} gap={'small'}>
      <Text type={type}>{formattedDate}</Text>
      {showSince ? <Tag style={{ margin: 0 }}>{timeAgo + ' ago'}</Tag> : null}
    </Flex>
  )
}

TimeDisplay.propTypes = {
  dateTime: PropTypes.string,
  showDate: PropTypes.bool,
  showTime: PropTypes.bool,
  showSince: PropTypes.bool,
  type: PropTypes.string
}

export default TimeDisplay
