<script setup>
import { ref, onMounted, watch } from "vue";
import dayjs from "dayjs";
import useSearchParam from "@/hooks/useSearchParam";
import { useI18n } from "vue-i18n";
const { t, locale } = useI18n();
const { searchParams, changeParams } = useSearchParam();

const dateRange = ref([
  {
    key: "start_at",
    value: searchParams.value.Start_date
      ? dayjs(searchParams.value.Start_date)
      : dayjs().subtract(30, "day"),
    dateFormat: "yyyy-MM-dd",
    placeholder: t("alert.start_date"),
  },
  {
    key: "end_at",
    value: searchParams.value.End_date
      ? dayjs(searchParams.value.End_date)
      : dayjs(),
    dateFormat: "yyyy-MM-dd",
    placeholder: t("alert.end_date"),
  },
]);

const changeTimeRange = () => {
  const newRange = [
    {
      key: "start_at",
      value: dayjs().subtract(30, "day"), 
      dateFormat: "yyyy-MM-dd",
      placeholder: t("alert.start_date"),
    },
    {
      key: "end_at",
      value: dayjs().endOf("day"), 
      dateFormat: "yyyy-MM-dd",
      placeholder: t("alert.end_date"),
    },
  ];

  dateRange.value = newRange;

  changeParams({
    ...searchParams.value,
    Start_date: newRange[0].value,
    End_date: newRange[1].value,
  });
};

onMounted(() => {
  // 初始化日期範圍
  if (
    !searchParams.value.Start_date ||
    !searchParams.value.End_date
  ) {
    changeTimeRange();
  }
});

// 監聽搜尋變化
watch(
  dateRange,
  () => {
    changeParams({
      ...searchParams.value,
      Start_date: dayjs(dateRange.value[0].value).format("YYYY-MM-DD"),
      End_date: dayjs(dateRange.value[1].value).format("YYYY-MM-DD"),
    });
  },
  { deep: true } // 確保在初始化立即觸發
);

watch(locale, () => {
  dateRange.value[0].placeholder = t("alert.start_date");
  dateRange.value[1].placeholder = t("alert.end_date");
});
</script>

<template>
  <div class="flex flex-wrap items-center">
    <button
      type="button"
      class="btn btn-outline-success mr-3"
      @click="changeTimeRange"
    >
      {{ $t("alert.30days") }}
    </button>
    <DateGroup :items="dateRange" :withLine="true" />
  </div>
</template>

<style lang="scss" scoped></style>
