<script setup>
import { computed, ref, useAttrs } from "vue";
import { useLightInputDefaults } from "../../composables/useLightProps";
import { useI18n } from "vue-i18n";
defineOptions({ inheritAttrs: false });
const { t } = useI18n();
const modelValue = defineModel({ type: null });
const props = defineProps({
  modelValue: { type: null, required: false },
  label: { type: String, required: false },
  hint: { type: String, required: false },
  nowBtn: { type: Boolean, required: false },
  withSeconds: { type: Boolean, required: false },
  format24h: { type: Boolean, required: false, default: true },
  hideBottomSpace: { type: Boolean, required: false, default: true },
  color: { type: String, required: false },
  disable: { type: Boolean, required: false },
  readonly: { type: Boolean, required: false },
  dark: { type: Boolean, required: false }
});
const attrs = useAttrs();
const popup = ref(null);
const TIME_KEYS = ["nowBtn", "withSeconds", "format24h"];
const base = useLightInputDefaults(props, attrs, TIME_KEYS);
const inputProps = computed(() => ({
  ...base.value,
  mask: props.withSeconds ? "##:##:##" : "##:##",
  rules: rules.value
}));
const rules = computed(() => {
  const r = [];
  r.push((v) => {
    if (!v) return true;
    const parts = v.split(":");
    const valid2 = parts.length === 2 && parseInt(parts[0]) >= 0 && parseInt(parts[0]) <= 23 && parseInt(parts[1]) >= 0 && parseInt(parts[1]) <= 59;
    const valid3 = parts.length === 3 && parseInt(parts[0]) >= 0 && parseInt(parts[0]) <= 23 && parseInt(parts[1]) >= 0 && parseInt(parts[1]) <= 59 && parseInt(parts[2]) >= 0 && parseInt(parts[2]) <= 59;
    return valid2 || valid3 || t("Invalid time format");
  });
  return r;
});
const timeProps = computed(() => ({
  format24h: props.format24h,
  nowBtn: props.nowBtn,
  withSeconds: props.withSeconds,
  ...props.color !== void 0 && { color: props.color },
  ...props.dark !== void 0 && { dark: props.dark },
  ...props.disable !== void 0 && { disable: props.disable }
}));
</script>

<template>
    <q-input v-model="modelValue" v-bind="inputProps">
        <template #prepend>
            <q-icon name="sym_o_access_time" class="cursor-pointer">
                <q-popup-proxy cover transition-show="scale" transition-hide="scale" ref="popup">
                    <q-time v-model="modelValue" v-bind="timeProps">
                        <div class="row items-center justify-end">
                            <q-btn v-close-popup :label="$t('Close')" flat />
                        </div>
                    </q-time>
                </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>
