<script setup>
import { ref, watch, watchEffect, nextTick, computed } from "vue";
import { VTextField } from "vuetify/components/VTextField";
import { VueDatePicker as Datepicker } from "@vuepic/vue-datepicker";
import "@vuepic/vue-datepicker/dist/main.css";
import { th, enUS } from "date-fns/locale";
import { Datetime } from "../../utils/datetime";
const props = defineProps({
  enableSeconds: { type: Boolean, required: false, default: false },
  locale: { type: String, required: false, default: "TH" },
  pickerOnly: { type: Boolean, required: false, default: false },
  modelValue: { type: [String, null], required: false }
});
const emit = defineEmits(["update:modelValue"]);
const time = ref(null);
const tempTime = ref(null);
const datepickerLocale = computed(() => props.locale === "TH" ? th : enUS);
const datepickerTimeConfig = computed(() => ({
  enableSeconds: props.enableSeconds,
  minutesGridIncrement: 1
}));
const isMenuOpen = ref(false);
const isTextFieldFocused = ref(false);
const isTextFieldTyped = ref(false);
function onTextFieldFocus(event) {
  isTextFieldFocused.value = true;
  nextTick(() => {
    event.target.select();
  });
}
function onTextFieldTyped() {
  if (!isTextFieldTyped.value) {
    isTextFieldTyped.value = true;
    isMenuOpen.value = false;
  }
}
function onTextFieldBlur() {
  if (isTextFieldTyped.value) {
    setTime(tempTime.value);
    isTextFieldTyped.value = false;
  }
  isTextFieldFocused.value = false;
}
function onTextFieldEnterKey() {
  onTextFieldBlur();
}
function onTextFieldClear() {
  reset();
}
function reset() {
  time.value = null;
  tempTime.value = null;
}
function setTime(TimeString) {
  const dateTime = Datetime().fromStringTime(TimeString, void 0, props.locale);
  if (!dateTime.luxonDateTime.isValid) {
    tempTime.value = null;
    time.value = null;
  } else {
    time.value = dateTime.toFormat("HH:mm:ss", "EN");
    tempTime.value = time.value;
  }
}
function setDatePicker(DateString) {
  setTime(DateString);
}
watchEffect(() => {
  if (!isTextFieldFocused.value && time.value) {
    const dateTime = Datetime().fromString(time.value, void 0, props.locale);
    tempTime.value = dateTime.toFormat(props.enableSeconds ? "HH:mm:ss" : "HH:mm", props.locale);
  } else {
    tempTime.value = time.value;
  }
});
watch(time, (newValue) => {
  if (!isMenuOpen.value) emit("update:modelValue", newValue);
});
watch(isMenuOpen, () => {
  if (isMenuOpen.value && !time.value) {
    time.value = Datetime().now().toFormat(props.enableSeconds ? "HH:mm:ss" : "HH:mm:00");
  }
  if (!isMenuOpen.value) emit("update:modelValue", time.value);
});
watch(() => props.modelValue, () => {
  setTime(props.modelValue || null);
}, { immediate: true });
function toggleMenuOpen(trigger) {
  if (trigger === "textField" && props.pickerOnly || trigger === "icon" && !props.pickerOnly) {
    if (!props.readonly) isMenuOpen.value = true;
  }
}
const textFieldRef = ref();
function validate() {
  textFieldRef.value?.validate();
}
function resetValidation() {
  textFieldRef.value?.resetValidation();
}
defineExpose({
  reset,
  validate,
  resetValidation,
  isValid: textFieldRef.value?.isValid
});
</script>

<template>
  <v-menu
      v-model="isMenuOpen"
      :close-on-content-click="false"
      :open-on-click="false"
  >
    <template #activator="{ props }">
      <v-text-field
          ref="textFieldRef"
          v-model="tempTime"
          v-bind="$attrs"
          @focus="onTextFieldFocus"
          @blur="onTextFieldBlur"
          @keydown="onTextFieldTyped"
          @keyup.enter="onTextFieldEnterKey"
          @click:clear="onTextFieldClear"
          @click="toggleMenuOpen('textField')"
      >
        <template #append="{ isReadonly, isDisabled }">
          <v-icon
              :disabled="isReadonly.value || isDisabled.value"
              v-bind="props"
              @click="toggleMenuOpen('icon')"
          >
            fa:fa-regular fa-clock
          </v-icon>
        </template>
      </v-text-field>
    </template>
    <Datepicker
        v-model="time"
        model-type="HH:mm:ss"
        :time-config="datepickerTimeConfig"
        time-picker
        auto-apply
        :close-on-auto-apply="false"
        inline
        :locale="datepickerLocale"
        @update:model-value="setDatePicker"
    />
  </v-menu>
</template>
