export function formatTraceDateTime(date: string | undefined) {
  if (!date) return ''

  return new Date(date).toLocaleString()
}

export function parseMDY(str: string) {
  if (!str || !/^\d{2}\/\d{2}\/\d{4}$/.test(str)) {
    return null
  }
  const [mm, dd, yyyy] = str.split('/')
  const d = new Date(+yyyy, +mm - 1, +dd)
  return isNaN(d.getTime()) ? null : d
}

export function smallDateFromISO(inputDate: string) {
  const date = new Date(inputDate)

  const month = date.getMonth() + 1
  const day = date.getDate()
  const year = date.getFullYear()

  const formattedMonth = month < 10 ? `0${month}` : `${month}`
  const formattedDay = day < 10 ? `0${day}` : `${day}`

  return `${formattedMonth}/${formattedDay}/${year}`
}

export function dateToTimeShort(date: Date) {
  const milliseconds = String(date.getMilliseconds()).padStart(3, '0')
  const timeFormatter = new Intl.DateTimeFormat(undefined, {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  })

  return `${timeFormatter.format(date)},${milliseconds}`
}

export function dateToTimeOnly(date: Date | string | undefined) {
  if (!date) return ''
  if (typeof date === 'string') {
    date = new Date(date)
  }
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${hours}:${minutes}:${seconds}`
}
export function dateToDateSort(date: Date) {
  const dateFormatter = new Intl.DateTimeFormat(undefined, {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  })

  return dateFormatter.format(date)
}
