<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_created_at
      ? dayjs(searchParams.value.start_created_at).valueOf()
      : dayjs().subtract(30, "day").valueOf(),
    dateFormat: "yyyy-MM-dd",
    placeholder: t("alert.start_date"),
  },
  {
    key: "end_at",
    value: searchParams.value.end_created_at
      ? dayjs(searchParams.value.end_created_at).valueOf()
      : dayjs().valueOf(),
    dateFormat: "yyyy-MM-dd",
    placeholder: t("alert.end_date"),
  },
]);

const changeTimeRange = () => {
  const newRange = [
    {
      key: "start_at",
      value: dayjs().subtract(30, "day").startOf("day").valueOf(), // 向前推30天並設置為當天的00:00:00.000
      dateFormat: "yyyy-MM-dd",
      placeholder: t("alert.start_date"),
    },
    {
      key: "end_at",
      value: dayjs().endOf("day").valueOf(), // 設置為今日的23:59:59.999
      dateFormat: "yyyy-MM-dd",
      placeholder: t("alert.end_date"),
    },
  ];

  dateRange.value = newRange;

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

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

// 監聽搜尋變化
watch(
  dateRange,
  () => {
    changeParams({
      ...searchParams.value,
      start_created_at: dayjs(dateRange.value[0].value)
        .startOf("day")
        .valueOf(),
      end_created_at: dayjs(dateRange.value[1].value).endOf("day").valueOf(),
    });
  },
  { 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 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>
