<template>
  <div class="q-gutter-sm">
    <h6 class="text-center text-bold q-ma-md text-primary">{{ props.title }}</h6>
    <div class="row">
      <q-checkbox
        style="min-width: 75px"
        dense
        v-for="opt in weekdayOptions"
        :key="opt.value"
        v-model="selectedWeekdays"
        :val="opt.value"
        :label="opt.label"
      />
    </div>
    <div class="row">
      <q-date v-model="dateRange" range flat />
      <div>
        <q-badge color="secondary"> Total dates selected: {{ filteredDates.length }} </q-badge>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { date } from 'quasar';
import { i18n } from 'src/boot/lang';

const props = defineProps({
  title: String,
});

const startDate = new Date();

// Initial range (format: YYYY/MM/DD)
const dateRange = ref();
const selectedWeekdays = ref([0, 3]); // Default to weekdays

onMounted(() => {
  dateRange.value = date.formatDate(startDate, 'YYYY/MM/DD');
});

const weekdayOptions = [
  { label: i18n.global.t('MondayShort'), value: 1 },
  { label: i18n.global.t('TuesdayShort'), value: 2 },
  { label: i18n.global.t('WednesdayShort'), value: 3 },
  { label: i18n.global.t('ThursdayShort'), value: 4 },
  { label: i18n.global.t('FridayShort'), value: 5 },
  { label: i18n.global.t('SaturdayShort'), value: 6 },
  { label: i18n.global.t('SundayShort'), value: 0 },
];

// The Logic: Calculate all specific dates within the range that match weekdays
const filteredDates = computed(() => {
  if (!dateRange.value) {
    return [];
  } else if (typeof dateRange.value === 'string') {
    const current = new Date(dateRange.value);
    if (current !== undefined && selectedWeekdays.value.includes(current.getDay())) {
      return [date.formatDate(current, 'YYYY/MM/DD')];
    }
    return [];
  }

  const end = new Date(dateRange.value.to);
  const result = [];

  let current = new Date(dateRange.value.from);

  while (current <= end) {
    if (selectedWeekdays.value.includes(current.getDay())) {
      result.push(date.formatDate(current, 'YYYY/MM/DD'));
    }
    current = date.addToDate(current, { days: 1 });
  }
  return result;
});
</script>
