<template>
  <w-input
    ref="qDateInput"
    v-bind="$props"
    :model-value="formatToLocalDate(modelValue)"
    :placeholder="placeholder"
    :clearable="false"
    :editable="false"
    @click="showDatePopup()"
  >
    <template #append>
      <q-icon
        v-if="showCalendarIcon"
        class="cursor-pointer"
        name="fal fa-calendar-alt"
        @click.stop.prevent="showDatePopup()"
      />
      <q-icon
        v-if="modelValue && clearable"
        class="cursor-pointer"
        name="fal fa-times-circle"
        @click.stop.prevent="clearDate()"
      />
      <div>
        <q-popup-proxy
          ref="qDateProxy"
          transition-show="scale"
          transition-hide="scale"
        >
          <q-date
            :model-value="data"
            :options="options"
            :default-year-month="defaultYearMonth"
            @update:model-value="onInput"
          />
        </q-popup-proxy>
      </div>
    </template>
  </w-input>
</template>

<script>
import moment from "moment";
import WInput from "../input/WInput";

export default {
  name: "WDateInput",
  mixins: [WInput],
  inheritAttrs: true,
  props: {
    modelValue: {
      type: [Object, String, Date],
      default: null,
    },
    defaultYearMonth: {
      type: String,
      default: moment().format("YYYY/MM"),
    },
    showCalendarIcon: {
      type: Boolean,
      default: true,
    },
    placeholder: {
      type: String,
      default: "",
    },
    options: {
      type: [Array, Function, undefined],
      default: undefined,
    },
  },
  emits: ["update:modelValue"],
  computed: {
    data() {
      return this.modelValue ? this.formatToLocalDate(this.modelValue) : null;
    },
  },
  methods: {
    hideDatePopup() {
      this.$refs.qDateProxy.hide();
    },
    showDatePopup() {
      this.$refs.qDateProxy.show();
    },
    onInput(value) {
      this.hideDatePopup();
      // standard quasar component does not return timestamp
      // "YYYY/MM/DD" is not a recognized RFC2822 or ISO format.
      // So we need to tell moment.js the format of the date quasar is giving us, otherwise we will get a warning
      this.$emit("update:modelValue", moment(value, "YYYY/MM/DD").toDate());
      this.$refs.qDateInput.blur();
    },
    formatToLocalDate(value) {
      return moment(value).isValid()
        ? moment(value).local().format("YYYY/MM/DD")
        : null;
    },
    clearDate(value) {
      this.hideDatePopup();
      this.$emit("update:modelValue", null);
      this.$refs.qDateInput.blur();
    },
  },
};
</script>
