<script setup>
import { blankEvent, sharedState } from "@/views/apps/calendar/useCalendar";
import { PerfectScrollbar } from "vue3-perfect-scrollbar";
import { VForm } from "vuetify/lib/components/VForm";
import { useCalendarStore } from "./useCalendarStore";

// 👉 store
const props = defineProps({
  isDrawerOpen: {
    type: Boolean,
    required: true,
  },
  event: {
    type: null,
    required: true,
  },
});

const emit = defineEmits([
  "update:isDrawerOpen",
  "addEvent",
  "updateEvent",
  "removeEvent",
]);

const store = useCalendarStore();
const refForm = ref();
const userData = useCookie("userData");
const project_number = ref("");
const project_name = ref("");
const initial_date = ref("");
const work_duration = ref("");

// Fetch project data
const fetchProjectData = async () => {
  try {
    const response = await $api(`/pdet/project/show`, {
      method: "POST",
      body: JSON.stringify({ project_number: import.meta.env.VITE_PROJECT_NUMBER }),
    });
    console.log(response);
    project_number.value = response.no;
    project_name.value = response.name;
    initial_date.value = response.expectedBeginAt;
    work_duration.value = response.work_duration;
  } catch (error) {
    console.error("Error fetching project data:", error);
  }
};

// Fetch data on component mount
onMounted(() => {
  fetchProjectData();
});

//時間範圍、固定星期幾的選項
const timeFilterOption = ref(null);
//一天、多天、多筆不連續日期的選項
const dateChoice = ref(null);

//時間範圍 一天
const range_one_day_exempt_date = ref(null);
const range_one_day_duration_unit = ref("全天");

//時間範圍 多天
const range_multiple_days_start_date = ref(null);
const range_multiple_days_end_date = ref(null);
const range_multiple_days_duration_unit = ref("全天");

//時間範圍 多筆不連續日期
const inconcecuticeDateChoice = ref(null);

//時間範圍 多筆不連續日期 一天
const inconcecutive_days_single_day = ref(null);
const inconcecutive_days_single_day_duration_unit = ref("全天");

//時間範圍 多筆不連續日期 多天
const inconcecutive_days_multiple_days_start_date = ref(null);
const inconcecutive_days_multiple_days_end_date = ref(null);
const inconcecutive_days_multiple_days_duration_unit = ref("全天");

//顯示所有多筆不連續日期的資料
const dateHistory = ref([]);

//固定星期幾
const fixedWeekdayOption = ref(null);

//固定星期幾 整個專案
const weekdaysDropdownWholeProject = ref([]);
const weekdaysDurationUnitWholeProject = ref("全天");

//固定星期幾 時間範圍
const weekdaysDropdownSelectRange = ref([]);
const weekdaysDurationUnitSelectRange = ref("全天");
//固定星期幾 時間範圍 開始日期、結束日期
const projectRange = ref({ start: "", end: "" });

const showDateOptions = ref(false);
const today = new Date().toISOString().substring(0, 10);

const handleAddDate = () => {
  showDateOptions.value = true;
};

//顯示所有多筆不連續日期的資料
const confirmDateSelection = () => {
  let formattedDate;
  let durationUnit;

  switch (inconcecuticeDateChoice.value) {
    case "多天":
      if (
        inconcecutive_days_multiple_days_start_date.value &&
        inconcecutive_days_multiple_days_end_date.value &&
        inconcecutive_days_multiple_days_duration_unit.value
      ) {
        formattedDate = `${inconcecutive_days_multiple_days_start_date.value} 到 ${inconcecutive_days_multiple_days_end_date.value}`;
        durationUnit = mapDurationUnit(
          inconcecutive_days_multiple_days_duration_unit.value
        );
      }
      break;
    case "一天":
      if (
        inconcecutive_days_single_day.value &&
        inconcecutive_days_single_day_duration_unit.value
      ) {
        formattedDate = inconcecutive_days_single_day.value;
        durationUnit = mapDurationUnit(
          inconcecutive_days_single_day_duration_unit.value
        );
      }
      break;
  }

  // Ensure all required data is present before adding to history
  if (formattedDate && durationUnit) {
    dateHistory.value.push({
      date: formattedDate,
      duration: durationUnit,
    });
  } else {
    console.error("Some fields are empty, not adding to history.");
  }
  resetDateSelection();
};

function mapDurationUnit(unit) {
  switch (unit) {
    case "one day":
      return "全天";
    case "half day":
      return "半天";
    default:
      return unit; // Default case returns the input unit unchanged
  }
}

function resetDateSelection() {
  inconcecuticeDateChoice.value = null;
  inconcecutive_days_single_day.value = null;
  inconcecutive_days_single_day_duration_unit.value = null;
  inconcecutive_days_multiple_days_start_date.value = null;
  inconcecutive_days_multiple_days_end_date.value = null;
  inconcecutive_days_multiple_days_duration_unit.value = null;

  showDateOptions.value = false;
}

// 👉 Event
const event = ref({
  ...JSON.parse(JSON.stringify(props.event)),
});

const resetEvent = () => {
  event.value = {
    ...JSON.parse(JSON.stringify(props.event)),
  };

  nextTick(() => {
    refForm.value?.resetValidation();
  });
};

watch(
  () => props.isDrawerOpen,
  (val) => {
    if (!val) {
      resetEvent();
      resetAllFields();
    }
  }
);

const removeEvent = () => {
  const eventData = {
    eventId: String(event.value.id),
    project_number: project_number.value,
    username: userData.value.name,
  };
  emit("removeEvent", eventData);

  // Close drawer
  emit("update:isDrawerOpen", false);
};

const handleSubmit = () => {
  refForm.value?.validate().then(({ valid }) => {
    if (valid) {
      event.value.project_number = project_number.value;
      event.value.title = event.value.exempt_type;
      event.value.allDay = true;
      switch (timeFilterOption.value) {
        case "range":
          switch (dateChoice.value) {
            case "one day":
              // 單一日期處理
              event.value.start = range_one_day_exempt_date.value;
              event.value.duration_unit = range_one_day_duration_unit.value;
              event.value.username = userData.value.name;
              event.value.choice = "一天";
              event.value.logOnce = 0;
              if (event.value.id) {
                emit("updateEvent", event.value);
              } else {
                emit("addEvent", event.value);
              }

              break;
            case "multiple days":
              // 多天處理
              event.value.start = range_multiple_days_start_date.value;
              event.value.end = range_multiple_days_end_date.value;
              event.value.duration_unit =
                range_multiple_days_duration_unit.value;
              event.value.username = userData.value.name;
              event.value.choice = "多天";
              event.value.logOnce = 0;
              emit("addEvent", event.value);
              break;
            case "inconcecutive days":
              // 處理多筆不連續日期
              let eventsToEmit = dateHistory.value.map((dateItem, index) => {
                const newEvent = { ...event.value };

                // 解析日期範圍或單一日期
                if (dateItem.date.includes("到")) {
                  let [startDate, endDate] = dateItem.date.split("到");
                  newEvent.start = startDate.trim();
                  newEvent.end = endDate.trim();
                } else {
                  newEvent.start = dateItem.date;
                  delete newEvent.end; // 確保沒有結束日期
                }

                // 處理工期單位，移除括號
                newEvent.duration_unit = dateItem.duration.replace(/[()]/g, "");
                newEvent.username = userData.value.name;
                newEvent.choice = "多筆不連續日期";
                newEvent.logOnce = index === 0;

                return newEvent;
              });

              Promise.all(
                eventsToEmit.map(
                  (e) =>
                    new Promise((resolve) => {
                      emit("addEvent", e, () => resolve());
                    })
                )
              ).then(() => {
                // console.log("所有非連續日期事件已經發送");
              });

              break;
          }
          break;
        case "weekday":
          if (fixedWeekdayOption.value === "whole project") {
            try {
              // 處理整個專案的固定星期幾
              const startDate = new Date(initial_date.value); // 初始日期
              const durationDays = parseInt(work_duration.value, 10); // 工作天數
              const endDate = new Date(startDate);
              endDate.setDate(endDate.getDate() + durationDays);

              const weekdays = weekdaysDropdownWholeProject.value.map(
                (day) =>
                ({
                  Monday: 1,
                  Tuesday: 2,
                  Wednesday: 3,
                  Thursday: 4,
                  Friday: 5,
                  Saturday: 6,
                  Sunday: 0,
                }[day])
              );

              const exemptDates = getExemptDates(startDate, endDate, weekdays);

              let eventsToEmit = exemptDates.map((date) => {
                const newEvent = {
                  ...event.value,
                  start: date,
                  duration_unit: weekdaysDurationUnitWholeProject.value,
                  username: userData.value.name,
                  choice: "全專案固定星期幾",
                };
                delete newEvent.end;
                return newEvent;
              });
              console.log(eventsToEmit)

              emit("addEvents", eventsToEmit);
            } catch (error) {
              console.error("處理固定星期幾事件時發生錯誤：", error);
            }
          } else if (fixedWeekdayOption.value === "select range yourself") {
            // 處理自選日期範圍的固定星期幾
            try {
              const startDate = new Date(projectRange.value.start); // 起始日期
              const endDate = new Date(projectRange.value.end); // 結束日期

              const weekdays = weekdaysDropdownSelectRange.value.map(
                (day) =>
                ({
                  Monday: 1,
                  Tuesday: 2,
                  Wednesday: 3,
                  Thursday: 4,
                  Friday: 5,
                  Saturday: 6,
                  Sunday: 0,
                }[day])
              );

              const exemptDates = getExemptDates(startDate, endDate, weekdays);

              let eventsToEmit = exemptDates.map((date) => {
                const newEvent = {
                  ...event.value,
                  start: date,
                  duration_unit: weekdaysDurationUnitSelectRange.value,
                  username: userData.value.name,
                  choice: "自選日期固定星期幾",
                };
                delete newEvent.end;
                return newEvent;
              });

              emit("addEvents", eventsToEmit);
            } catch (error) {
              console.error("處理固定星期幾事件時發生錯誤：", error);
            }
          }
          break;
      }

      resetEventData();
      resetAllFields();

      // Close drawer
      emit("update:isDrawerOpen", false);
    }
  });
};

function getExemptDates(startDate, endDate, weekdays) {
  let dates = [];
  let currentDate = new Date(startDate);
  while (currentDate <= endDate) {
    if (weekdays.includes(currentDate.getDay())) {
      dates.push(new Date(currentDate));
    }
    currentDate.setDate(currentDate.getDate() + 1);
  }
  return dates.map((date) => date.toISOString().split("T")[0]);
}

function resetEventData() {
  event.value = structuredClone(blankEvent); // Assuming `blankEvent` is your initial empty state
  resetDateSelection();
}

// 新增清空所有參數的方法
function resetAllFields() {
  timeFilterOption.value = null;
  dateChoice.value = null;
  range_one_day_exempt_date.value = null;
  range_one_day_duration_unit.value = null;
  range_multiple_days_start_date.value = null;
  range_multiple_days_end_date.value = null;
  range_multiple_days_duration_unit.value = null;
  inconcecuticeDateChoice.value = null;
  inconcecutive_days_single_day.value = null;
  inconcecutive_days_single_day_duration_unit.value = null;
  inconcecutive_days_multiple_days_start_date.value = null;
  inconcecutive_days_multiple_days_end_date.value = null;
  inconcecutive_days_multiple_days_duration_unit.value = null;
  dateHistory.value = [];
  fixedWeekdayOption.value = null;
  weekdaysDropdownWholeProject.value = [];
  weekdaysDropdownSelectRange.value = [];
  projectRange.value = { start: "", end: "" };
  showDateOptions.value = false;
}

// 👉 Form
const onCancel = () => {
  // Close drawer
  emit("update:isDrawerOpen", false);
  nextTick(() => {
    refForm.value?.reset();
    resetEvent();
    refForm.value?.resetValidation();
  });
};

const startDateTimePickerConfig = computed(() => {
  const config = {
    enableTime: !event.value.allDay,
    dateFormat: `Y-m-d${event.value.allDay ? "" : " H:i"}`,
  };

  if (event.value.end) config.maxDate = event.value.end;

  return config;
});

const endDateTimePickerConfig = computed(() => {
  const config = {
    enableTime: !event.value.allDay,
    dateFormat: `Y-m-d${event.value.allDay ? "" : " H:i"}`,
  };

  if (event.value.start) config.minDate = event.value.start;

  return config;
});

const dialogModelValueUpdate = (val) => {
  emit("update:isDrawerOpen", val);
};

watch(
  () => sharedState.eventDetails,
  (newVal) => {
    if (newVal) {
      event.value.id = newVal.id;
      event.value.title = newVal.title;
      event.value.start = newVal.start;
      event.value.end = newVal.end;
      event.value.allDay = newVal.allDay;
      event.value.exempt_type = newVal.exempt_type;
      event.value.exempt_reason = newVal.exempt_reason;
      event.value.duration_unit = newVal.duration_unit;
      event.value.project_number = project_number;
      timeFilterOption.value = "range";
      dateChoice.value = "one day";
      range_one_day_exempt_date.value = newVal.end;
      range_one_day_duration_unit.value = newVal.duration_unit;
    }
  },
  { immediate: true }
);
</script>

<template>
  <VNavigationDrawer
    temporary
    location="end"
    :model-value="props.isDrawerOpen"
    width="420"
    class="scrollable-content"
    @update:model-value="dialogModelValueUpdate">
    <!-- 👉 Header -->
    <AppDrawerHeaderSection
      :title="event.id ? '更新篩選條件' : '新增篩選條件'"
      @cancel="$emit('update:isDrawerOpen', false)">
      <template #beforeClose>
        <IconBtn v-show="event.id" @click="removeEvent">
          <VIcon size="18" icon="tabler-trash" />
        </IconBtn>
      </template>
    </AppDrawerHeaderSection>

    <PerfectScrollbar :options="{ wheelPropagation: false }">
      <VCard flat>
        <VCardText>
          <!-- SECTION Form -->
          <VForm ref="refForm" @submit.prevent="handleSubmit">
            <VCol cols="12">
              <AppSelect v-model="event.exempt_type" label="選擇不被計入工期的類型" placeholder="選擇不被計入工期的類型"
                :rules="[requiredValidator]" :items="store.availableCalendars" :item-title="(item) => item.label"
                :item-value="(item) => item.label">
                <template #selection="{ item }">
                  <div
                    v-show="event.exempt_type"
                    class="align-center"
                    :class="event.exempt_type ? 'd-flex' : ''">
                    <VBadge
                      :color="item.raw.color"
                      inline
                      dot
                      class="pa-1 pb-2" />
                    <span>{{ item.raw.label }}</span>
                  </div>
                </template>
              </AppSelect>
            </VCol>

            <VCol cols="12">
              <AppTextField v-model="event.exempt_reason" label="不被計入工期的原因" placeholder="輸入不被計入工期的原因" />
            </VCol>

            <VCol cols="12">
              <!--時間範圍、固定星期幾-->
              <AppSelect v-model="timeFilterOption" label="選擇工期篩選方式" placeholder="選擇工期篩選方式" :rules="[requiredValidator]"
                :items="store.timeFilterOptions" :item-title="(item) => item.label"
                :item-value="(item) => item.value" />
            </VCol>

            <!--選擇時間範圍-->
            <VCol cols="12" v-if="timeFilterOption === 'range'">
              <!--一天、多天、多筆不連續日期-->
              <AppSelect v-model="dateChoice" label="選擇不計工期的天數" placeholder="選擇不計工期的天數" :rules="[requiredValidator]"
                :items="store.dateTypes" :item-title="(item) => item.label" :item-value="(item) => item.value">
                <template #selection="{ item }">
                  <div>
                    <span>{{ item.raw.label }}</span>
                  </div>
                </template>
              </AppSelect>
            </VCol>

            <!--選擇一天-->
            <VCol cols="12" v-if="dateChoice === 'one day' && timeFilterOption === 'range'">
              <AppDateTimePicker v-model="range_one_day_exempt_date" label="輸入日期" placeholder="輸入日期" />

              <!--全天、半天-->
              <AppSelect v-model="range_one_day_duration_unit" label="選擇工期單位" placeholder="選擇工期單位"
                :rules="[requiredValidator]" :items="store.durationUnits" :item-title="(item) => item.label"
                :item-value="(item) => item.label">
                <template #selection="{ item }">
                  <div
                    v-show="range_one_day_duration_unit"
                    class="align-center"
                    :class="range_one_day_duration_unit ? 'd-flex' : ''">
                    <span>{{ item.raw.label }}</span>
                  </div>
                </template>
              </AppSelect>
            </VCol>

            <!--選擇多天-->
            <VCol cols="12" v-if="
              dateChoice === 'multiple days' && timeFilterOption === 'range'
            ">
              <AppDateTimePicker v-model="range_multiple_days_start_date" label="輸入起始日期" placeholder="輸入起始日期" />
              <AppDateTimePicker v-model="range_multiple_days_end_date" label="輸入結束日期" placeholder="輸入結束日期" />
              <!--全天、半天-->
              <AppSelect v-model="range_multiple_days_duration_unit" label="選擇工期單位" placeholder="選擇工期單位"
                :rules="[requiredValidator]" :items="store.durationUnits" :item-title="(item) => item.label"
                :item-value="(item) => item.label">
                <template #selection="{ item }">
                  <div
                    v-show="range_multiple_days_duration_unit"
                    class="align-center"
                    :class="range_multiple_days_duration_unit ? 'd-flex' : ''">
                    <span>{{ item.raw.label }}</span>
                  </div>
                </template>
              </AppSelect>
            </VCol>

            <!--選擇不計工期的天數-->
            <VCol cols="12" v-if="showDateOptions">
              <AppSelect v-model="inconcecuticeDateChoice" label="選擇不計工期的天數" :items="['一天', '多天']" />
            </VCol>

            <VCol cols="12" v-if="
              showDateOptions &&
              dateChoice === 'inconcecutive days' &&
              inconcecuticeDateChoice === '一天'
            ">
              <AppDateTimePicker v-model="inconcecutive_days_single_day" label="輸入日期" placeholder="輸入日期" />

              <!--全天、半天-->
              <AppSelect v-model="inconcecutive_days_single_day_duration_unit" label="選擇工期單位" placeholder="選擇工期單位"
                :rules="[requiredValidator]" :items="store.durationUnits" :item-title="(item) => item.label"
                :item-value="(item) => item.label">
                <template #selection="{ item }">
                  <div
                    v-show="inconcecutive_days_single_day_duration_unit"
                    class="align-center"
                    :class="inconcecutive_days_single_day_duration_unit
                        ? 'd-flex'
                        : ''
                      ">
                    <span>{{ item.raw.label }}</span>
                  </div>
                </template>
              </AppSelect>
            </VCol>

            <!--選擇多天-->
            <VCol cols="12" v-if="
              showDateOptions &&
              dateChoice === 'inconcecutive days' &&
              inconcecuticeDateChoice === '多天'
            ">
              <AppDateTimePicker v-model="inconcecutive_days_multiple_days_start_date" label="輸入起始日期"
                placeholder="輸入起始日期" />
              <AppDateTimePicker v-model="inconcecutive_days_multiple_days_end_date" label="輸入結束日期"
                placeholder="輸入結束日期" />
              <!--全天、半天-->
              <AppSelect v-model="inconcecutive_days_multiple_days_duration_unit" label="選擇工期單位" placeholder="選擇工期單位"
                :rules="[requiredValidator]" :items="store.durationUnits" :item-title="(item) => item.label"
                :item-value="(item) => item.label">
                <template #selection="{ item }">
                  <div
                    v-show="inconcecutive_days_multiple_days_duration_unit"
                    class="align-center"
                    :class="inconcecutive_days_multiple_days_duration_unit
                        ? 'd-flex'
                        : ''
                      ">
                    <span>{{ item.raw.label }}</span>
                  </div>
                </template>
              </AppSelect>
            </VCol>

            <VCol v-if="showDateOptions" cols="4" class="d-flex align-end">
              <VBtn block @click="confirmDateSelection">確定</VBtn>
            </VCol>

            <VCol cols="12" v-if="
              !showDateOptions &&
              dateChoice === 'inconcecutive days' &&
              timeFilterOption === 'range'
            ">
              <VBtn block @click="handleAddDate">新增日期</VBtn>
            </VCol>

            <VCol cols="12">
              <!-- Display selected date and duration -->
              <div v-for="(item, index) in dateHistory" :key="index" class="my-2">
                {{ item.date }} ({{ item.duration }})
              </div>
            </VCol>

            <!--選擇固定星期幾-->
            <VCol cols="12" v-if="timeFilterOption === 'weekday'">
              <!--整個專案、自行輸入時間範圍-->
              <AppSelect v-model="fixedWeekdayOption" label="選擇固定星期幾的日期篩選範圍" placeholder="選擇固定星期幾的日期篩選範圍"
                :items="store.timeframe" :item-title="(item) => item.label" :item-value="(item) => item.value" />

              <!--選擇整個專案-->
              <VCol cols="12" v-if="
                timeFilterOption === 'weekday' &&
                fixedWeekdayOption === 'whole project'
              ">
                <!-- 可複選星期一到星期日 -->
                <AppSelect v-model="weekdaysDropdownWholeProject" label="選擇星期幾(可複選)" placeholder="選擇星期幾(可複選)"
                  :items="store.weekdays" :item-title="(item) => item.label" :item-value="(item) => item.value"
                  multiple />
                <AppSelect v-model="weekdaysDurationUnitWholeProject" label="選擇工期單位" placeholder="選擇工期單位"
                  :rules="[requiredValidator]" :items="store.durationUnits" :item-title="(item) => item.label"
                  :item-value="(item) => item.label">
                  <template #selection="{ item }">
                    <div
                      v-show="weekdaysDurationUnitWholeProject"
                      class="align-center"
                      :class="weekdaysDurationUnitWholeProject ? 'd-flex' : ''">
                      <span>{{ item.raw.label }}</span>
                    </div>
                  </template>
                </AppSelect>
              </VCol>

              <!--選擇自行輸入時間範圍-->
              <VCol cols="12" v-if="
                timeFilterOption === 'weekday' &&
                fixedWeekdayOption === 'select range yourself'
              ">
                <AppDateTimePicker v-model="projectRange.start" label="起始日期" placeholder="選擇起始日期" />
                <AppDateTimePicker v-model="projectRange.end" label="結束日期" placeholder="選擇結束日期" />
                <!-- 可複選星期一到星期日 -->
                <AppSelect v-model="weekdaysDropdownSelectRange" label="選擇星期幾(可複選)" placeholder="選擇星期幾(可複選)"
                  :items="store.weekdays" :item-title="(item) => item.label" :item-value="(item) => item.value"
                  multiple />
                <AppSelect v-model="weekdaysDurationUnitSelectRange" label="選擇工期單位" placeholder="選擇工期單位"
                  :rules="[requiredValidator]" :items="store.durationUnits" :item-title="(item) => item.label"
                  :item-value="(item) => item.label">
                  <template #selection="{ item }">
                    <div
                      v-show="weekdaysDurationUnitSelectRange"
                      class="align-center"
                      :class="weekdaysDurationUnitSelectRange ? 'd-flex' : ''">
                      <span>{{ item.raw.label }}</span>
                    </div>
                  </template>
                </AppSelect>
              </VCol>
            </VCol>

            <!-- 👉 Form buttons -->
            <VCol cols="12">
              <VBtn type="submit" class="me-3"> 確認 </VBtn>
              <VBtn variant="outlined" color="secondary" @click="onCancel">
                取消
              </VBtn>
            </VCol>
          </VForm>
          <!-- !SECTION -->
        </VCardText>
      </VCard>
    </PerfectScrollbar>
  </VNavigationDrawer>
</template>
