<script lang='ts' setup>
import type { FieldBindingObject } from "vee-validate";

interface Props extends FieldBindingObject {
  datetime: string;
  label?: string;
  formatterValue?: (value: string) => string;
  format?: (value: string) => string;
  min?: string;
  max?: string;
}

const props = defineProps<Props>();
const emit = defineEmits<{
  (e: "update:value", value: string): void;
}>();
const model = defineModel({ type: String, required: true });
function handleChange(value: string) {
  const formattedValue = props.formatterValue ? props.formatterValue(value) : new Date(value).toISOString();
  model.value = formattedValue;
  props.onChange(formattedValue);
  emit("update:value", formattedValue);
}

function formatDisplay(value: string) {
  return props.format ? props.format(value) : useDateFormat(value, "YYYY/MM/DD").value;
}
</script>

<template>
  <div class="flex flex-col items-start">
    <ion-label class="text-sm font-bold color-(--ion-text-color-secondary) mb-3.5">
      {{ props.label }}
    </ion-label>
    <ion-datetime-button :datetime="datetime" color="primary">
      <div slot="date-target">
        {{ formatDisplay(props.value) }}
      </div>
    </ion-datetime-button>
    <ion-modal :keep-contents-mounted="true">
      <ion-datetime
        :id="datetime"
        class="ui-datetime"
        done-text="Done"
        presentation="date-time"
        :show-default-buttons="true"
        :min="props.min"
        :max="props.max"
        @ion-change="handleChange($event.detail.value as string)"
      />
    </ion-modal>
  </div>
</template>

<style lang='css' scoped></style>
