<template>
  <span
    v-if="isWording"
    class="tw:text-xs tw:font-normal"
    @click="handleClick"
    :class="{ 'tw:cursor-pointer': enableCopyToClipboard }"
    :aria-label="
      enableCopyToClipboard
        ? t('core.copyToClipboard$name', {
            name: `'${formattedTimestamp}'`,
          })
        : undefined
    "
    :role="enableCopyToClipboard ? 'button' : undefined"
  >
    <v-tooltip interactive>
      <template v-slot:activator="{ props: activatorProps }">
        <span v-bind="activatorProps">
          {{ $t("core.timeAgo", { time: timeAgo }) }}
        </span>
      </template>
      <div>
        {{ formattedTimestamp }}
      </div>
    </v-tooltip>
  </span>
  <span v-else>{{ formattedTimestamp }}</span>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref } from "vue"
import { differenceInDays } from "date-fns"
import { format, formatDistance } from "@racletteOrchestrator/helpers/date-fns"
import { useI18n } from "vue-i18n"
import { copyToClipboard } from "@racletteOrchestrator/helpers/uiHelper"

const props = defineProps<{
  timestamp: string
  enableCopyToClipboard?: boolean
}>()

const { t } = useI18n()

const now = ref(new Date())

const isWording = computed(() => {
  const date = new Date(props.timestamp)

  const diffDays = differenceInDays(now.value, date)

  return diffDays < 7
})

const timeAgo = computed(() => {
  const date = new Date(props.timestamp)

  return formatDistance(date, now.value)
})

const formattedTimestamp = computed(() => {
  const date = new Date(props.timestamp)

  return format(date, "PPpp")
})

const handleClick = () => {
  if (props.enableCopyToClipboard) {
    copyToClipboard(formattedTimestamp.value, formattedTimestamp.value)
  }
}

onMounted(() => setInterval(() => (now.value = new Date()), 60000))
</script>
