<script setup>
import { ref, computed, watch, useAttrs } from "vue";
import {} from "quasar";
import { useLightInputDefaults } from "../../composables/useLightProps";
defineOptions({ inheritAttrs: false });
const modelValue = defineModel({ type: null, ...{
  type: [String, Object, null],
  default: null
} });
const props = defineProps({
  name: { type: String, required: false },
  landscape: { type: Boolean, required: false, skipCheck: true },
  mask: { type: String, required: false },
  locale: { type: null, required: false },
  calendar: { type: null, required: false },
  color: { type: Object, required: false },
  textColor: { type: null, required: false },
  dark: { type: [Boolean, null], required: false, default: void 0 },
  square: { type: Boolean, required: false, default: void 0 },
  flat: { type: Boolean, required: false, skipCheck: true },
  bordered: { type: Boolean, required: false, skipCheck: true },
  readonly: { type: Boolean, required: false },
  disable: { type: Boolean, required: false, default: false },
  title: { type: null, required: false },
  subtitle: { type: null, required: false },
  defaultYearMonth: { type: null, required: false },
  defaultView: { type: null, required: false },
  yearsInMonthView: { type: Boolean, required: false, skipCheck: true },
  events: { type: [Array, Function], required: false, skipCheck: true },
  eventColor: { type: [String, Function], required: false, skipCheck: true },
  options: { type: [Array, Function], required: false, skipCheck: true },
  navigationMinYearMonth: { type: null, required: false },
  navigationMaxYearMonth: { type: null, required: false },
  noUnset: { type: Boolean, required: false, skipCheck: true },
  firstDayOfWeek: { type: null, required: false },
  todayBtn: { type: Boolean, required: false, skipCheck: true, default: true },
  minimal: { type: Boolean, required: false, skipCheck: true },
  multiple: { type: Boolean, required: false, skipCheck: true },
  range: { type: Boolean, required: false, skipCheck: true, default: false },
  emitImmediately: { type: Boolean, required: false, skipCheck: true },
  "onUpdate:modelValue": { type: Function, required: false },
  onNavigation: { type: Function, required: false },
  onRangeStart: { type: Function, required: false },
  onRangeEnd: { type: Function, required: false },
  fillMask: { type: [Boolean, String], required: false, skipCheck: true },
  reverseFillMask: { type: Boolean, required: false, skipCheck: true },
  unmaskedValue: { type: Boolean, required: false, skipCheck: true },
  maskTokens: { type: null, required: false },
  error: { type: [Boolean, null], required: false, skipCheck: true },
  errorMessage: { type: null, required: false },
  noErrorIcon: { type: Boolean, required: false, skipCheck: true },
  rules: { type: null, required: false },
  reactiveRules: { type: Boolean, required: false, skipCheck: true },
  lazyRules: { type: [Boolean, String], required: false, skipCheck: true },
  label: { type: null, required: false },
  stackLabel: { type: Boolean, required: false, skipCheck: true, default: void 0 },
  hint: { type: null, required: false },
  hideHint: { type: Boolean, required: false, skipCheck: true },
  prefix: { type: null, required: false },
  suffix: { type: null, required: false },
  labelColor: { type: null, required: false },
  bgColor: { type: null, required: false },
  loading: { type: Boolean, required: false, skipCheck: true },
  clearable: { type: Boolean, required: false, skipCheck: true },
  clearIcon: { type: null, required: false },
  filled: { type: Boolean, required: false, skipCheck: true, default: void 0 },
  outlined: { type: Boolean, required: false, skipCheck: true, default: void 0 },
  borderless: { type: Boolean, required: false, skipCheck: true },
  standout: { type: [Boolean, String], required: false, skipCheck: true, default: void 0 },
  labelSlot: { type: Boolean, required: false, skipCheck: true },
  bottomSlots: { type: Boolean, required: false, skipCheck: true },
  hideBottomSpace: { type: Boolean, required: false, skipCheck: true, default: true },
  counter: { type: Boolean, required: false, skipCheck: true },
  rounded: { type: Boolean, required: false, skipCheck: true, default: void 0 },
  dense: { type: Boolean, required: false, skipCheck: true, default: void 0 },
  itemAligned: { type: Boolean, required: false, skipCheck: true },
  autofocus: { type: Boolean, required: false, skipCheck: true },
  for: { type: null, required: false },
  shadowText: { type: null, required: false },
  type: { type: null, required: false },
  debounce: { type: null, required: false },
  maxlength: { type: null, required: false },
  autogrow: { type: Boolean, required: false, skipCheck: true },
  inputClass: { type: null, required: false },
  inputStyle: { type: null, required: false },
  onFocus: { type: Function, required: false },
  onBlur: { type: Function, required: false },
  onClear: { type: Function, required: false }
});
const attrs = useAttrs();
const DATE_KEYS = [
  "range",
  "todayBtn",
  "locale",
  "calendar",
  "defaultYearMonth",
  "defaultView",
  "events",
  "eventColor",
  "emitImmediately",
  "yearsInMonthView",
  "navigationMinYearMonth",
  "navigationMaxYearMonth",
  "noUnset",
  "firstDayOfWeek",
  "minimal",
  "options",
  "subtitle",
  "title"
];
const popup = ref(null);
const inputValue = computed({
  get() {
    if (!modelValue.value) return "";
    if (typeof modelValue.value === "object" && modelValue.value.from) {
      return modelValue.value.from + (modelValue.value.to ? " to " + modelValue.value.to : "");
    }
    return modelValue.value || "";
  },
  set(val) {
    if (!val) {
      modelValue.value = null;
      return;
    }
    if (props.range) {
      const parts = val.split(" to ");
      if (parts.length === 2) {
        const [from, to] = parts;
        if (from.match(/^\d{4}-\d{2}-\d{2}$/) && to.match(/^\d{4}-\d{2}-\d{2}$/)) {
          modelValue.value = { from, to };
          return;
        }
        if (from.match(/^\d{4}-\d{2}-\d{2}$/) && !to) {
          modelValue.value = from;
          return;
        }
      }
      modelValue.value = null;
    } else {
      modelValue.value = val;
    }
  }
});
watch(modelValue, (val) => {
  if (!props.range || typeof val === "object" && val?.from && val?.to) {
    popup.value?.hide();
  }
}, { deep: true });
const inputMask = computed(
  () => props.range ? "####-##-## to ####-##-##" : "####-##-##"
);
const inputRules = computed(() => {
  if (props.range) return [];
  return [(val) => {
    if (val && !val.match(/^\d{4}-\d{2}-\d{2}$/))
      return "Invalid date format";
  }];
});
const base = useLightInputDefaults(props, attrs, DATE_KEYS);
const inputProps = computed(() => ({
  ...base.value,
  mask: inputMask.value,
  rules: inputRules.value
}));
const SHARED_KEYS = ["color", "dark", "disable", "readonly"];
const dateProps = computed(() => {
  const result = {};
  for (const key of [...DATE_KEYS, ...SHARED_KEYS]) {
    const val = props[key];
    if (val !== void 0) result[key] = val;
  }
  return result;
});
</script>

<template>
    <q-input :model-value="inputValue" @update:model-value="inputValue = $event"
        v-bind="inputProps">
        <template #prepend>
            <q-icon name="sym_o_event" class="cursor-pointer">
                <q-popup-proxy cover transition-show="scale" transition-hide="scale" ref="popup">
                    <q-date mask="YYYY-MM-DD" v-model="modelValue" v-bind="dateProps">
                        <div class="row items-center justify-end">
                            <q-btn v-close-popup :label="$t('Close')" flat />
                        </div>
                    </q-date>
                </q-popup-proxy>
            </q-icon>
        </template>

        <template v-for="(_, name) in $slots" #[name]="slotProps" :key="name">
            <slot :name="name" v-bind="slotProps ?? {}"></slot>
        </template>
    </q-input>
</template>
