<script setup lang="ts">
import { date } from 'quasar';
import { useTimesheetStore } from 'src/stores/timesheet-store';
import { useTimesheetApi } from '../composables/use-timesheet-api';
import { computed, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import TimesheetShiftForm from '../components/timesheet/timesheet-shift-form.vue';
import type { CreateShiftPayload } from '../types/timesheet-shift-interface';


    const { locale } = useI18n();
    const timesheet_store = useTimesheetStore();
    const { this_week, saveTimesheetShifts } = useTimesheetApi();

    onMounted(async () => {
        await this_week();
    });

    const date_options: Intl.DateTimeFormatOptions = {
        day:   'numeric',
        month: 'long',
        year:  'numeric',
    };

    const timesheet_label = computed(() => {
        const dates = timesheet_store.current_timesheet.label.split('.');
        const start_date = new Intl.DateTimeFormat(locale.value, date_options).format(date.extractDate(dates[0] as string, 'YYYY-MM-DD'));
        const end_date = new Intl.DateTimeFormat(locale.value, date_options).format(date.extractDate(dates[1] as string, 'YYYY-MM-DD'));
       
        if ( dates.length === 1) {
            return {
                start_date: '_',
                end_date: '_',
            }
        }
        return { start_date, end_date };
    });

    const onSaveShifts = async (payload: CreateShiftPayload[]) => {
        await saveTimesheetShifts(payload);
    };
</script>


<template>
    <q-page
        padding
        class="q-pa-md bg secondary"
    >
        <div class="text-h4 row justify-center q-mt-lg text-uppercase text-weight-bolder text-grey-8">
            {{ $t('pageTitles.timeSheets') }}
        </div>
        <div class="row items-center justify-center q-py-none q-my-none">
            <div class="text-primary text-h6 text-uppercase">
                {{ timesheet_label.start_date }}
            </div>
            <div class="text-grey-8 text-weight-bold text-uppercase q-mx-md">
                {{ $t('timeSheet.dateRangesTo') }}
            </div>
            <div class="text-primary text-h6 text-uppercase">
                {{ timesheet_label.end_date }}
            </div>
        </div>
        <q-card class="q-mt-md">
            <q-inner-loading :showing="timesheet_store.is_loading"/>
            <TimesheetShiftForm @save="onSaveShifts"/>
        </q-card>
    </q-page>
</template>