<script setup>
import { ref, watch } from 'vue';
import { format, parse } from 'date-fns';
import CalendarPicker from "@/components/GanttChart/CalendarPicker.vue";

const props = defineProps({
  modelValue: {
    type: String,
    default: '1/1/2024', // เปลี่ยนเป็น format `d/M/yyyy`
  },
});

const emits = defineEmits(['update:modelValue']);
const selectedDate = ref(props.modelValue);
const showCalendar = ref(false);

// ✅ ฟังก์ชันแปลง `d/M/yyyy` → `YYYY-MM-DD`
const parseDate = (dateStr) => {
  return format(parse(dateStr, "d/M/yyyy", new Date()), "yyyy-MM-dd");
};



// ✅ ฟังก์ชันเพิ่ม/ลดวัน และอัปเดต `selectedDate`
const changeDate = (days) => {
  const currentDate = parse(selectedDate.value, "d/M/yyyy", new Date());
  const newDate = new Date(currentDate);
  newDate.setDate(currentDate.getDate() + days);
  selectedDate.value = format(newDate, 'd/M/yyyy');
};


// ✅ เมื่อ `selectedDate` เปลี่ยน ให้ emit ค่าออกไป
watch(selectedDate, (newVal) => {
  console.log("📅 GanttCalendar - วันที่เปลี่ยน:", newVal);
  emits('update:modelValue', newVal);
});

// เมื่อเปิดปฏิทิน ให้ `selectedDate` ซิงค์กับ `v-date-picker`


// ฟังก์ชันเปิดปฏิทิน
const openCalendar = () => {
  showCalendar.value = true;
  console.log("📅 ปุ่ม ... ถูกกด!");
};

// เมื่อเลือกวันที่ใน CalendarPicker จะปิด dialog
const closeCalendarDialog = () => {
  showCalendar.value = false;
};


</script>

<template>
  <v-container>
    <v-col cols="auto" class="d-inline-flex align-center"
      style="background-color: #7E9CD3; border-radius: 15px; max-width: fit-content; padding: 8px 16px;">

      <v-btn class="mr-2" style="background-color: #2B2E3F; color: white; border-radius: 10px;" @click="changeDate(-1)">
        &lt; Back
      </v-btn>

      <v-btn style="background-color: white; color: black; min-width: 200px; border-radius: 15px;">
        {{ selectedDate }}
      </v-btn>

      <v-btn class="ml-2" style="background-color: #2B2E3F; color: white; border-radius: 10px;" @click="changeDate(1)">
        Next &gt;
      </v-btn>

      <!-- ✅ เปลี่ยนจาก v-dialog เป็น v-menu (Popover) -->
      <v-menu v-model="showCalendar" :close-on-content-click="false" location="bottom">
        <template v-slot:activator="{ props }">
          <v-btn v-bind="props" class="ml-2 popover-btn">
            <v-icon>mdi-dots-horizontal</v-icon>
          </v-btn>
        </template>

        <!-- ✅ ปรับขนาด Popover และใช้ CalendarPicker -->
        <v-card class="pb-12 popover-card">
          <CalendarPicker v-model="selectedDate" @update:modelValue="closeCalendarDialog" />
        </v-card>
      </v-menu>

    </v-col>
  </v-container>
</template>

<style scoped>
/* ✅ ปรับแต่งปุ่ม "..." */
.popover-btn {
  background-color: white;
  color: black;
  border-radius: 10px;
}

/* ✅ ปรับแต่งขนาดและขอบโค้งของ Popover */
.popover-card {
  border-radius: 25px !important;
  /* ✅ กำหนดขอบโค้ง */

  box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.2);
  background-color: white;
}
</style>