<template>
  <a-time-picker
    v-model="selected"
    type="time-range"
    :format="format"
    :style="{ width: '200px' }"
    v-bind="attrs"
    @change="onChange"
  />
</template>

<script setup lang="ts">
  import { ref, watch, useAttrs } from 'vue';

  defineOptions({
    name: 'SelectRangeDatetime',
  });

  type TimeType = string | undefined;

  const props = withDefaults(
    defineProps<{
      startTime: TimeType;
      endTime: TimeType;
      format?: string;
    }>(),
    {
      format: 'HH:mm',
    }
  );
  const emit = defineEmits(['update:startTime', 'update:endTime', 'change']);
  const attrs = useAttrs();

  const selected = ref<string[]>();

  function onChange(value: any) {
    const vals = (value || []) as TimeType[];
    emit('update:startTime', vals[0]);
    emit('update:endTime', vals[1]);
    emit('change', vals);
  }

  watch(
    () => [props.startTime, props.endTime],
    (val) => {
      selected.value = [val[0] || '', val[1] || ''];
    },
    {
      immediate: true,
    }
  );
</script>
