<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="mergedError"
    :success="success"
    :clearable="clearable"
    :editable="editable"
    :input-class="inputClass"
    :label-class="labelClass"
    :group-class="groupClass"
    v-bind="$attrs"
    @clear="onClear"
    @commit="onCommit"
  >
    <template #default="{ currentMonth, currentYear, close }">
      <MonthGrid
        :month="currentMonth"
        :year="currentYear"
        :selected-date="modelValue ?? null"
        :min="min"
        :max="max"
        @select="(iso) => onSelect(iso, close)"
      />
    </template>
  </CalendarField>
</template>

<script setup lang="ts">
import {computed, ref, watch} from 'vue'
import CalendarField from './internal/CalendarField.vue'
import MonthGrid from './internal/MonthGrid.vue'
import {formatIsoToDisplay, isDateInRange, isValidIso, parseDisplayToIso} 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
    editable?: boolean
    invalidMessage?: string
    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,
    editable: false,
    invalidMessage: 'Date invalide',
    inputClass: '',
    labelClass: '',
    groupClass: '',
  },
)

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

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

const internalError = ref('')
const mergedError = computed(() => props.error || internalError.value)

const onCommit = (text: string) => {
  const trimmed = text.trim()
  if (trimmed === '') {
    internalError.value = ''
    emit('update:modelValue', null)
    return
  }
  const iso = parseDisplayToIso(trimmed)
  if (iso && isDateInRange(iso, props.min, props.max)) {
    internalError.value = ''
    emit('update:modelValue', iso)
    return
  }
  internalError.value = props.invalidMessage
}

const onClear = () => {
  internalError.value = ''
  emit('update:modelValue', null)
}

const onSelect = (iso: string, close: () => void) => {
  internalError.value = ''
  emit('update:modelValue', iso)
  close()
}

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