<template>
  <span v-if="relativeTo" class="ui-relative-time">
    <BmsTooltip :tooltip-text="formattedDate">
      {{ date }}
    </BmsTooltip>
  </span>
</template>

<script setup lang="ts">
import { relativeDate } from '@/helpers/date.helper';
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
import BmsTooltip from '@/components/feedback/BmsTooltip.vue';

interface BmsRelativeTimeProps {
  relativeTo?: number;
}

const props = withDefaults(defineProps<BmsRelativeTimeProps>(), {
  relativeTo: Date.now(),
});

const emit = defineEmits(['change']);

const timeout = ref<any>();
const date = ref<string>();

const formattedDate = computed(() => {
  return new Date(props.relativeTo)?.toLocaleString('fr-FR') ?? '';
});

onMounted(() => {
  setDate();
});

onBeforeUnmount(() => {
  clearTimeout(timeout.value);
});

const setDate = () => {
  if (!props.relativeTo) {
    return;
  }

  const { diff, value } = relativeDate({
    to: props.relativeTo,
  });

  const timeoutDelay = diff < 60 ? 10000 : 30000;

  date.value = value;
  emit('change', diff);

  timeout.value = setTimeout(() => {
    setDate();
  }, timeoutDelay);
};
</script>
