<template>
  <CalendarField
    :id="id"
    :display-value="displayValue"
    :sync-to="modelValue ?? null"
    :name="name"
    :label="label"
    :placeholder="placeholder"
    :required="required"
    :disabled="disabled"
    :readonly="readonly"
    :hint="hint"
    :error="error"
    :success="success"
    :clearable="clearable"
    :input-class="inputClass"
    :label-class="labelClass"
    :group-class="groupClass"
    v-bind="$attrs"
    @clear="emit('update:modelValue', null)"
  >
    <template #default="{ currentMonth, currentYear, close }">
      <MonthGrid
        :month="currentMonth"
        :year="currentYear"
        :selected-date="modelValue ?? null"
        :min="min"
        :max="max"
        @select="(iso) => { emit('update:modelValue', iso); close() }"
      />
    </template>
  </CalendarField>
</template>

<script setup lang="ts">
import {computed, watch} from 'vue'
import CalendarField from './internal/CalendarField.vue'
import MonthGrid from './internal/MonthGrid.vue'
import {formatIsoToDisplay, isValidIso} from './composables/dateFormat'

defineOptions({name: 'MalioDate', inheritAttrs: false})

const props = withDefaults(
  defineProps<{
    id?: string
    name?: string
    label?: string
    modelValue?: string | null
    placeholder?: string
    required?: boolean
    disabled?: boolean
    readonly?: boolean
    hint?: string
    error?: string
    success?: string
    min?: string
    max?: string
    clearable?: boolean
    inputClass?: string
    labelClass?: string
    groupClass?: string
  }>(),
  {
    id: '',
    name: '',
    label: '',
    modelValue: undefined,
    placeholder: 'JJ/MM/AAAA',
    required: false,
    disabled: false,
    readonly: false,
    hint: '',
    error: '',
    success: '',
    min: undefined,
    max: undefined,
    clearable: true,
    inputClass: '',
    labelClass: '',
    groupClass: '',
  },
)

const emit = defineEmits<{(e: 'update:modelValue', value: string | null): void}>()

const displayValue = computed(() => formatIsoToDisplay(props.modelValue ?? null))

watch(() => props.modelValue, (val) => {
  if (val && !isValidIso(val) && import.meta.dev) {
    console.warn(`[MalioDate] modelValue invalide ignoré : "${val}"`)
  }
})
</script>
