<!--
Sélecteur de dates
-->

<template>
  <main>
    <div class="d-flex flex-column">
      <span>{{ $t(fieldLabel) }}</span>

      <UiDatePicker
          v-model="date"
          :readonly="readonly"
          :format="format"
          @update:model-value="onUpdate($event)"
          @change="onChange($event)"
      />

      <span v-if="error || !!fieldViolations" class="theme-danger">
        {{ errorMessage || fieldViolations ? $t(fieldViolations) : '' }}
      </span>
    </div>
  </main>
</template>

<script setup lang="ts">
import {useFieldViolation} from "~/composables/form/useFieldViolation";
import {formatISO} from "date-fns";

const props = defineProps({
  /**
   * v-model
   */
  modelValue: {
    type: String,
    required: false,
    default: null
  },
  field: {
    type: String,
    required: false,
    default: null
  },
  label: {
    type: String,
    required: false,
    default: null
  },
  readonly: {
    type: Boolean,
    required: false
  },
  format: {
    type: String,
    required: false,
    default: null
  },
  error: {
    type: Boolean,
    required: false
  },
  errorMessage: {
    type: String,
    required: false,
    default: null
  }
})

const input = ref(null)

const {fieldViolations, updateViolationState} = useFieldViolation(props.field)

const fieldLabel = props.label ?? props.field

const emit = defineEmits(['update:model-value', 'change'])

const date: Ref<Date> = ref(new Date(props.modelValue))
console.log(date.value)

const onUpdate = (event: string) => {
  emit('update:model-value', formatISO(date.value))
}

const onChange = (event: Event | undefined) => {
  updateViolationState(event)
  emit('change', formatISO(date.value))
}
</script>

<style scoped>

</style>
