<template>
  <!-- @see https://vue3datepicker.com/props/modes/#multi-calendars -->
  <VueDatePicker
      :model-value="modelValue"
      range
      multi-calendars
      :auto-apply="autoApply"
      :locale="i18n.locale.value"
      :format-locale="fnsLocale"
      :format="dateFormatPattern"
      :start-date="today"
      :teleport="true"
      :alt-position="dateRangePickerAltPosition"
      :enable-time-picker="false"
      close-on-scroll
      text-input
      :select-text="$t('select')"
      :cancel-text="$t('cancel')"
      input-class-name="date-range-picker-input"
      @update:model-value="updateDateTimeRange"
      class="date-range-picker"
      :style="style"
  />
</template>

<script setup lang="ts">
import DateUtils, {supportedLocales} from "~/services/utils/dateUtils";
import {PropType} from "@vue/runtime-core";

const props = defineProps({
  modelValue: {
    type: Array as PropType<Array<Date> | null>,
    required: false,
    default: null
  },
  maxHeight: {
    type: Number,
    required: false,
    default: null
  }
})

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

const autoApply = false

const updateDateTimeRange = (value: [string, string]) => {
  emit('update:modelValue', value)
}

const i18n = useI18n()

const fnsLocale = DateUtils.getFnsLocale(i18n.locale.value as supportedLocales)
const dateFormatPattern = DateUtils.getShortFormatPattern(i18n.locale.value as supportedLocales)

const today = new Date()

let style = '';
if (props.maxHeight !== null) {
  style += 'height: ' + props.maxHeight + 'px;max-height: ' + props.maxHeight + 'px;'
}

/**
 * Recalcule la position du panneau de sélection des dates si trop près du bord droit de l'écran
 * @param el
 */
const dateRangePickerAltPosition = (el: HTMLElement) => {
  let xOffset = 0
  const fullWidth = 500
  const rightPadding = 30
  const rect = el.getBoundingClientRect()

  if ((rect.left + fullWidth + rightPadding) > window.innerWidth) {
    xOffset = window.innerWidth - (rect.left + fullWidth + rightPadding)
  }

  return {
    top: rect.bottom,
    left: rect.left + xOffset
  }
}
</script>

<style scoped lang="scss">
  :deep(div[role="textbox"]) {
    height: 100% !important;
    max-height: 100% !important;
  }

  :deep(.dp__input_wrap) {
    height: 100% !important;
    max-height: 100% !important;
  }

  :deep(.date-range-picker-input) {
      height: 100% !important;
      max-height: 100% !important;
  }
</style>
