<script setup>
import { onMounted, watch, computed, ref, useAttrs } from 'vue';
import { date } from 'quasar';
import VnDate from './VnDate.vue';
import { useRequired } from 'src/composables/useRequired';

const $attrs = useAttrs();
const { isRequired, requiredFieldRule } = useRequired($attrs);

const $props = defineProps({
    isOutlined: {
        type: Boolean,
        default: false,
    },
    isPopupOpen: {
        type: Boolean,
        default: false,
    },
    multiple: {
        type: Boolean,
        default: true,
    },
});

const model = defineModel({
    type: [String, Date, Array],
    default: null,
});

const vnInputDateRef = ref(null);

const dateFormat = 'DD/MM/YYYY';
const isPopupOpen = ref();
const hover = ref();
const mask = ref();

const mixinRules = [requiredFieldRule, ...($attrs.rules ?? [])];

const formattedDate = computed({
    get() {
        if (!model.value) return model.value;
        if ($props.multiple) {
            return model.value
                .map((d) => date.formatDate(new Date(d), dateFormat))
                .join(', ');
        }
        return date.formatDate(new Date(model.value), dateFormat);
    },
    set(value) {
        if (value == model.value) return;
        if ($props.multiple) return; // No permitir edición manual en modo múltiple

        let newDate;
        if (value) {
            // parse input
            if (value.includes('/') && value.length >= 10) {
                if (value.at(2) == '/') value = value.split('/').reverse().join('/');
                value = date.formatDate(
                    new Date(value).toISOString(),
                    'YYYY-MM-DDTHH:mm:ss.SSSZ',
                );
            }
            const [year, month, day] = value.split('-').map((e) => parseInt(e));
            newDate = new Date(year, month - 1, day);
            if (model.value && !$props.multiple) {
                const orgDate =
                    model.value instanceof Date ? model.value : new Date(model.value);

                newDate.setHours(
                    orgDate.getHours(),
                    orgDate.getMinutes(),
                    orgDate.getSeconds(),
                    orgDate.getMilliseconds(),
                );
            }
        }
        if (!isNaN(newDate)) model.value = newDate.toISOString();
    },
});

const popupDate = computed(() => {
    if (!model.value) return model.value;
    if ($props.multiple) {
        return model.value.map((d) => date.formatDate(new Date(d), 'YYYY/MM/DD'));
    }
    return date.formatDate(new Date(model.value), 'YYYY/MM/DD');
});
onMounted(() => {
    // fix quasar bug
    mask.value = '##/##/####';
    if ($props.multiple && !model.value) {
        model.value = [];
    }
});
watch(
    () => model.value,
    (val) => (formattedDate.value = val),
    { immediate: true },
);

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

const manageDate = (dates) => {
    if ($props.multiple) {
        model.value = dates.map((d) => new Date(d).toISOString());
    } else {
        formattedDate.value = dates;
    }
    if ($props.isPopupOpen) isPopupOpen.value = false;
};
</script>

<template>
    <div @mouseover="hover = true" @mouseleave="hover = false">
        <QInput
            ref="vnInputDateRef"
            v-model="formattedDate"
            class="vn-input-date"
            :mask="$props.multiple ? undefined : mask"
            placeholder="dd/mm/aaaa"
            v-bind="{ ...$attrs, ...styleAttrs }"
            :class="{ required: isRequired }"
            :rules="mixinRules"
            :clearable="false"
            @click="isPopupOpen = !isPopupOpen"
            @keydown="isPopupOpen = false"
            hide-bottom-space
            :data-cy="($attrs['data-cy'] ?? $attrs.label) + '_inputDate'"
        >
            <template #append>
                <QIcon
                    name="close"
                    size="xs"
                    v-if="
                        ($attrs.clearable == undefined || $attrs.clearable) &&
                        hover &&
                        model &&
                        !$attrs.disable
                    "
                    @click="
                        vnInputDateRef.focus();
                        model = null;
                        isPopupOpen = false;
                    "
                />
            </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"
            >
                <VnDate
                    v-model="popupDate"
                    @update:model-value="manageDate"
                    :multiple="multiple"
                />
            </QMenu>
            <QDialog v-else v-model="isPopupOpen">
                <VnDate
                    v-model="popupDate"
                    @update:model-value="manageDate"
                    :multiple="multiple"
                />
            </QDialog>
        </QInput>
    </div>
</template>
<i18n>
    es:
        Open date: Abrir fecha
</i18n>
