<script setup>
import { computed, ref } from 'vue';
import { toDate } from 'src/filters';

const props = defineProps({
    modelValue: {
        type: String,
        default: null,
    },
    readonly: {
        type: Boolean,
        default: false,
    },
    isOutlined: {
        type: Boolean,
        default: false,
    },
});
const emit = defineEmits(['update:modelValue']);
const value = computed({
    get() {
        return props.modelValue;
    },
    set(value) {
        emit('update:modelValue', value ? new Date(value).toISOString() : null);
    },
});

const isPopupOpen = ref(false);

const onDateUpdate = (date) => {
    value.value = date;
    isPopupOpen.value = false;
};

const padDate = (value) => value.toString().padStart(2, '0');
const formatDate = (dateString) => {
    const date = new Date(dateString || '');
    return `${date.getFullYear()}/${padDate(date.getMonth() + 1)}/${padDate(
        date.getDate()
    )}`;
};

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

<template>
    <QInput
        class="vn-input-date"
        rounded
        readonly
        :model-value="toDate(value)"
        v-bind="{ ...$attrs, ...styleAttrs }"
    >
        <template #append>
            <QIcon name="event" class="cursor-pointer">
                <QPopupProxy
                    v-model="isPopupOpen"
                    cover
                    transition-show="scale"
                    transition-hide="scale"
                    :no-parent-event="props.readonly"
                >
                    <QDate
                        :model-value="formatDate(value)"
                        @update:model-value="onDateUpdate"
                    />
                </QPopupProxy>
            </QIcon>
        </template>
    </QInput>
</template>

<style lang="scss">
.vn-input-date.q-field--standard.q-field--readonly .q-field__control:before {
    border-bottom-style: solid;
}

.vn-input-date.q-field--outlined.q-field--readonly .q-field__control:before {
    border-style: solid;
}
</style>
