<script setup lang="ts">
import DatePicker from 'primevue/datepicker'
import { computed } from 'vue'
const props = defineProps<{ modelValue: string | Date | null; inputId?: string; disabled?: boolean; invalid?: boolean; min?: Date; max?: Date }>()
const emit = defineEmits<{ 'update:modelValue': [value: string | Date | null]; blur: [event: Event] }>()
const dateValue = computed(() => {
  if (props.modelValue instanceof Date) return props.modelValue
  if (typeof props.modelValue === 'string') return new Date(props.modelValue)
  return null
})
const handleDateChange = (value: Date | Date[] | (Date | null)[] | null | undefined) => {
  if (value instanceof Date) emit('update:modelValue', value)
  else if (value === null || value === undefined) emit('update:modelValue', null)
  else emit('update:modelValue', value[0] ?? null)
}
</script>
<template>
  <DatePicker
    :input-id="inputId"
    :model-value="dateValue"
    :disabled="disabled"
    :invalid="invalid"
    :min-date="min"
    :max-date="max"
    date-format="yy-mm-dd"
    show-icon
    @update:model-value="handleDateChange"
    @blur="emit('blur', $event as unknown as Event)"
  />
</template>
