<script setup>
import { computed, ref, useAttrs } from 'vue';
import { useI18n } from 'vue-i18n';
import { date } from 'quasar';
import { useValidator } from 'src/composables/useValidator';
import VnTime from './VnTime.vue';

const { validations } = useValidator();
const $attrs = useAttrs();
const model = defineModel({ type: String });
const props = defineProps({
    timeOnly: {
        type: Boolean,
        default: false,
    },
    isOutlined: {
        type: Boolean,
        default: false,
    },
});
const vnInputTimeRef = ref(null);
const initialDate = ref(model.value ?? Date.vnNew());
const { t } = useI18n();
const requiredFieldRule = (val) => validations().required($attrs.required, val);
const mixinRules = [requiredFieldRule, ...($attrs.rules ?? [])];
const dateFormat = 'HH:mm';
const isPopupOpen = ref();
const hover = ref();

const styleAttrs = computed(() => {
    return props.isOutlined
        ? {
              dense: true,
              outlined: true,
              rounded: true,
          }
        : {};
});

const formattedTime = computed({
    get() {
        if (!model.value || model.value?.length <= 5) return model.value;
        return dateToTime(model.value);
    },
    set(value) {
        if (value == model.value) return;
        let time = value;
        if (time) {
            if (time?.length > 5) time = dateToTime(time);
            else {
                if (time.length == 1 && parseInt(time) > 2) time = time.padStart(2, '0');
                time = time.padEnd(5, '0');
                if (!time.includes(':'))
                    time = time.substring(0, 2) + ':' + time.substring(3, 5);
            }
            if (!props.timeOnly) {
                const [hh, mm] = time.split(':');

                const date = new Date(model.value ? model.value : initialDate.value);
                date.setHours(hh, mm, 0);
                time = date?.toISOString();
            }
        }
        model.value = time;
    },
});

function dateToTime(newDate) {
    return date.formatDate(new Date(newDate), dateFormat);
}
</script>
<template>
    <div @mouseover="hover = true" @mouseleave="hover = false">
        <QInput
            ref="vnInputTimeRef"
            class="vn-input-time"
            mask="##:##"
            placeholder="--:--"
            v-model="formattedTime"
            v-bind="{ ...$attrs, ...styleAttrs }"
            :class="{ required: $attrs.required }"
            style="min-width: 100px"
            :rules="mixinRules"
            @click="isPopupOpen = false"
            type="time"
            hide-bottom-space
        >
            <template #append>
                <QIcon
                    name="close"
                    size="xs"
                    v-if="
                        ($attrs.clearable == undefined || $attrs.clearable) &&
                        hover &&
                        model &&
                        !$attrs.disable
                    "
                    @click="
                        vnInputTimeRef.focus();
                        model = null;
                        isPopupOpen = false;
                    "
                />
                <QIcon
                    name="Schedule"
                    class="cursor-pointer"
                    @click="isPopupOpen = !isPopupOpen"
                    :title="t('Open time')"
                />
            </template>
            <QMenu
                v-if="$q.screen.gt.xs"
                transition-show="scale"
                transition-hide="scale"
                v-model="isPopupOpen"
                anchor="bottom left"
                self="top start"
                :no-focus="true"
                :no-parent-event="true"
            >
                <VnTime v-model="formattedTime" />
            </QMenu>
            <QDialog v-else v-model="isPopupOpen">
                <VnTime v-model="formattedTime" />
            </QDialog>
        </QInput>
    </div>
</template>
<style lang="scss">
.vn-input-time.q-field--standard.q-field--readonly .q-field__control:before {
    border-bottom-style: solid;
}

.vn-input-time.q-field--outlined.q-field--readonly .q-field__control:before {
    border-style: solid;
}
</style>
<style lang="scss" scoped>
:deep(input[type='time']::-webkit-calendar-picker-indicator) {
    display: none;
}
</style>
<i18n>
    es:
        Open time: Abrir tiempo
</i18n>
