<!--
Sélecteur de dates avec Vuetify

@see https://vuetifyjs.com/en/components/date-pickers/
-->

<template>
  <v-layout row wrap>
    <v-menu
      v-model="menu"
      :close-on-content-click="false"
      :nudge-right="40"
      lazy
      transition="scale-transition"
      offset-y
      :max-width="290"
      :min-width="290"
      :position-x="positionX"
      :position-y="positionY"
    >
      <template #activator="{ props: attrs }">
        <v-text-field
          v-model="displayDate"
          :label="label"
          :readonly="true"
          v-bind="attrs"
        />
      </template>

      <v-date-picker
        :model-value="modelValue"
        :locale="i18n.locale.value"
        no-title
        scrollable
        @update:model-value="updateDate"
      />
    </v-menu>
  </v-layout>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, watch, type PropType } from 'vue'
import { useI18n } from 'vue-i18n'

const props = defineProps({
  modelValue: Date,
  label: {
    type: String,
    default: '',
  },
  format: {
    type: String,
    default: null,
  },
  /**
   * Position du date-picker
   * @see https://vuetifyjs.com/en/api/v-menu/#props-position
   */
  position: {
    type: String as PropType<'left' | 'center' | 'right'>,
    default: 'center',
  },
})

const emit = defineEmits(['update:modelValue'])

const i18n = useI18n()
const menu = ref(false)
const positionX = ref(0)
const positionY = ref(0)

const displayDate = computed({
  get: () => {
    if (!props.modelValue) return ''
    if (props.format) {
      return new Intl.DateTimeFormat(i18n.locale.value, {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: props.withTime ? '2-digit' : undefined,
        minute: props.withTime ? '2-digit' : undefined,
      }).format(props.modelValue)
    }
    return props.modelValue.toLocaleDateString(i18n.locale.value)
  },
  set: () => {},
})

function updateDate(value: Date) {
  emit('update:modelValue', value)
  menu.value = false
}

function updatePosition() {
  nextTick(() => {
    const activator = document.querySelector('.v-menu__activator')
    if (activator) {
      const rect = activator.getBoundingClientRect()
      positionX.value = rect.left
      positionY.value = rect.bottom
    }
  })
}

watch(menu, (val) => {
  if (val) updatePosition()
})
</script>

<style scoped>
.v-menu__content {
  position: absolute !important;
}
</style>
