<template>
  <VmDatetimeField
    :model-value="modelValue || null"
    :precision="precision"
    :placeholder="placeholderText"
    :disabled="disabled"
    :style="{ width }"
    @update:model-value="onUpdate"
  />
</template>

<script setup lang="ts">
import { crudLabel } from '../style'
import { computed } from 'vue'
import { useCrud } from '../useCrud'
import VmDatetimeField from './vm-datetime-field.vue'
import type { DateTimePrecision } from '../../../shared/datetime-picker'

defineOptions({ name: 'vm-date-picker' })

const props = withDefaults(
  defineProps<{
    modelValue?: string | null
    type?: 'date' | 'datetime' | 'month' | 'year'
    prop?: string
    width?: string
    disabled?: boolean
    refreshOnChange?: boolean
    placeholder?: string
  }>(),
  {
    type: 'date',
    width: '160px',
    refreshOnChange: true,
  },
)

const emit = defineEmits<{
  'update:modelValue': [v: string]
  change: [v: string]
}>()

const crud = useCrud()

const TYPE_PRECISION: Record<string, DateTimePrecision> = {
  date: 'day',
  datetime: 'datetime',
  month: 'month',
  year: 'year',
}

const TYPE_PLACEHOLDER: Record<string, string> = {
  date: 'pickDate',
  datetime: 'pickDateTime',
  month: 'pickMonth',
  year: 'pickYear',
}

const precision = computed(
  () => TYPE_PRECISION[props.type] ?? ('day' as DateTimePrecision),
)

const placeholderText = computed(
  () => props.placeholder || crudLabel(TYPE_PLACEHOLDER[props.type] || 'pickDate'),
)

function onUpdate(v: string | null) {
  const out = v || ''
  emit('update:modelValue', out)
  emit('change', out)
  if (props.prop && props.refreshOnChange) {
    crud.refresh({ page: 1, [props.prop]: out || undefined })
  }
}
</script>
