<script setup lang="ts">
import { computed } from 'vue'

import { useFormatters } from '@/composables/useFormatters'

type TooltipDateValue = string | Date

const props = defineProps<{
  name: string
  start?: TooltipDateValue
  end?: TooltipDateValue
  timestamp?: TooltipDateValue
}>()

const { preciseTimeFormatter } = useFormatters()

function parseDate(value: TooltipDateValue | undefined): Date | null {
  if (!value) return null

  if (value instanceof Date) {
    return Number.isNaN(value.getTime()) ? null : value
  }

  const parsed = new Date(value)
  return Number.isNaN(parsed.getTime()) ? null : parsed
}

function formatDate(value: TooltipDateValue | undefined): string | null {
  const parsed = parseDate(value)
  if (!parsed) return null
  return preciseTimeFormatter.format(parsed)
}

const startText = computed(() => formatDate(props.start))
const endText = computed(() => formatDate(props.end))
const timestampText = computed(() => formatDate(props.timestamp))
</script>

<template>
  <div class="text-xs leading-5">
    <div class="grid grid-cols-[auto_1fr] gap-x-2">
      <span class="opacity-70">Name:</span>
      <span class="font-medium break-all">{{ props.name }}</span>

      <template v-if="startText">
        <span class="opacity-70">Start:</span>
        <span>{{ startText }}</span>
      </template>

      <template v-if="endText">
        <span class="opacity-70">End:</span>
        <span>{{ endText }}</span>
      </template>

      <template v-if="timestampText">
        <span class="opacity-70">Timestamp:</span>
        <span>{{ timestampText }}</span>
      </template>
    </div>
  </div>
</template>
