<template>
  <div class="vm-date-range" :class="{ 'is-disabled': disabled }">
    <VmDatetimeField
      class="vm-date-range__field"
      :model-value="modelValue?.[0] ?? null"
      :precision="precision"
      :placeholder="startPlaceholder ?? crudLabel('startTime')"
      :disabled="disabled"
      @update:model-value="(v) => set(0, v)"
    />
    <span class="vm-date-range__sep">-</span>
    <VmDatetimeField
      class="vm-date-range__field"
      :model-value="modelValue?.[1] ?? null"
      :precision="precision"
      :placeholder="endPlaceholder ?? crudLabel('endTime')"
      :disabled="disabled"
      @update:model-value="(v) => set(1, v)"
    />
  </div>
</template>

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

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

const props = withDefaults(
  defineProps<{
    modelValue?: Array<string | null>
    /** year | month | day | datetime */
    precision?: DateTimePrecision
    startPlaceholder?: string
    endPlaceholder?: string
    disabled?: boolean
  }>(),
  {
    precision: 'day',
    startPlaceholder: undefined,
    endPlaceholder: undefined,
  },
)

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

function set(idx: 0 | 1, v: string | null) {
  const next: Array<string | null> = [
    props.modelValue?.[0] ?? null,
    props.modelValue?.[1] ?? null,
  ]
  next[idx] = v
  emit('update:modelValue', next)
  emit('change', next)
}
</script>

<style lang="scss" scoped>
.vm-date-range {
  display: flex;
  box-sizing: border-box;
  width: 100%;
  align-items: center;

  &.is-disabled {
    opacity: 0.55;
    pointer-events: none;
  }
}

.vm-date-range__field {
  flex: 1 1 0;
  min-width: 0;
}

.vm-date-range__sep {
  flex: none;
  padding: 0 8px;
  color: var(--muted-foreground, #94a3b8);
  font-size: 13px;
  font-weight: 600;
  user-select: none;
}
</style>
