<script setup>
import { ref, computed, watch } from 'vue';
import { format, parse, parseISO, isValid } from 'date-fns';

const props = defineProps({
    modelValue: String, // ค่าที่รับมาจาก GanttCalendar.vue
});

const emits = defineEmits(["update:modelValue"]);

// ใช้ ref เก็บค่า selectedDate
const selectedDate = ref(props.modelValue ? parseDateDMY(props.modelValue) : new Date());

// ฟังก์ชันแปลง `d/M/yyyy` หรือ `yyyy-MM-dd` → `Date`
function parseDateDMY(dateString) {
    if (!dateString) return new Date();

    try {
        const parts = dateString.includes('-') ? dateString.split('-') : dateString.split('/');

        if (parts.length !== 3) throw new Error("Invalid date format");

        const day = parseInt(parts[0], 10);
        const month = parseInt(parts[1], 10) - 1; // `month` ใน JavaScript เริ่มที่ 0
        const year = parseInt(parts[2], 10);

        // ถ้าปีเป็นสองหลัก ให้บวก 2000 เข้าไป
        const fullYear = year < 100 ? year + 2000 : year;

        const parsedDate = new Date(fullYear, month, day);

        if (!isValid(parsedDate)) throw new Error("Invalid parsed date");

        return parsedDate;
    } catch (error) {
        console.error("📅 parseDateDMY ERROR:", error, "ค่าที่รับมา:", dateString);
        return new Date();
    }
}

// ฟังก์ชันแปลง `Date` → `d/M/yyyy`
const formattedDate = computed(() => {
    if (!selectedDate.value) return null;
    const date = new Date(selectedDate.value);
    return format(date, 'd/M/yyyy');
});

// watch `formattedDate` แล้ว emit กลับไปที่ `GanttCalendar.vue`
watch(formattedDate, (newValue) => {
    if (newValue !== null) {
        console.log("📅 CalendarPicker - ส่งค่ากลับไปเป็น:", newValue);
        emits("update:modelValue", newValue);
    }
});

// ฟังก์ชันอัปเดตวันที่จาก `v-date-picker`
const updateSelectedDate = (newValue) => {
    selectedDate.value = newValue;
};

// ฟังก์ชันสลับเปิด-ปิด Date Picker
const showDatePicker = ref(false);
const toggleDatePicker = () => {
    showDatePicker.value = !showDatePicker.value;
};

</script>

<template>
    <v-container>
        <v-row justify="center">
            <v-date-picker v-model="selectedDate" max="2025-12-31" min="2024-01-01" color="#96A9DB"
                @update:modelValue="updateSelectedDate">
            </v-date-picker>
        </v-row>
    </v-container>
</template>


<style scoped></style>