<!-- list of days with shifts infos-->

<script setup lang="ts">
/* eslint-disable */
import { computed, ref, watch } from 'vue';
import { useTimesheetStore } from 'src/stores/timesheet-store';
import TimesheetShiftComment from '../shift/timesheet-shift-comment.vue';
import TimesheetNavigation from './timesheet-navigation.vue';
import type { CreateShiftPayload } from '../../types/timesheet-shift-interface';
import { useTimesheetApi } from '../../composables/use-timesheet-api';
import { date as qdate } from 'quasar';

type ShiftRow = { 
    type: string;
    start_time: string;
    end_time: string;
    comment: string;
    is_approved: boolean;
}

const emit = defineEmits<{
    (e: 'save', payload: CreateShiftPayload[]): void;
}>();

const timesheet_store = useTimesheetStore();
const timesheet_api = useTimesheetApi();

const shift_type = ref<string[]> (['Régulier','Télétravail', 'Soir', 'Urgence', 'Férier', 'Vacance', 'Maladie']);
const days = ['Dimanche', 'Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'];
const empty_row = { type: '', start_time: '', end_time: '', comment: '', is_approved: false };

//Week dates
const week_dates = computed(() => {
    const start_date = timesheet_store.current_timesheet.start_day;
    if(!start_date) return [];

    const mm = /^(\d{4})-(\d{2})-(\d{2})$/.exec(start_date);
    if(!mm) return [];
    const year = Number(mm[1]), month = Number(mm[2]), day = Number(mm[3])

    const base = new Date(year, month - 1, day);
    const yyyymmdd = (date: Date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2,'0')}-${String(date.getDate()).padStart(2,'0')}`;
    return Array.from({length:7 }, (_, i) => {
        const date = new Date(base);
        date.setDate(base.getDate() + i);
        return yyyymmdd(date);
    });
});

//filling timesheet with shifts
const rows = ref<ShiftRow[]>(
    days.map((_,index) => {
        const date_ISO = week_dates.value[index];
        const shift = timesheet_store.current_timesheet.shifts.find(sh => sh.date === date_ISO);
        return shift ? {
                        type: shift.bank_type || '',
                        start_time: shift.start_time || '',
                        end_time: shift.end_time || '',
                        comment: shift.description || '',
                        is_approved: !!shift.is_approved,
                        }
                     : { ...empty_row };
    })
);

const show_comment = ref(false);
const selected_index = ref<number | null>(null);
const selected_row = computed<ShiftRow | undefined>(()=>
    selected_index.value != null ? rows.value[selected_index.value] : undefined
);

const is_calendar_limit = computed( () => {
    return  timesheet_store.current_pay_period.pay_year === 2024 && 
            timesheet_store.current_pay_period.pay_period_no <= 1;
});

const onDateSelected = async (date_string: string) => {
    const when = qdate.extractDate(date_string, 'YYYY-MM-DD');
    timesheet_api.getCurrentWeekTimesheetOverview(when);
};

const setComment = (comment: string) => {
    if(selected_row.value) {
        selected_row.value.comment = comment;
    }
    show_comment.value = false;
}

const onClickComment = (index: number)=> {
    selected_index.value = index;
    show_comment.value = true;
};

const buildPayload = (): CreateShiftPayload[] => {
    const dates = week_dates.value;
    if(!Array.isArray(dates) || dates.length === 0) return [];

    return rows.value.flatMap((row, idx) => {
        const date = dates[idx];
        const has_data = !!(row.type || row.start_time || row.end_time || row.comment);
        if(!date || !has_data) return [];

        const item: CreateShiftPayload = {
            date,
            type: row.type,
            start_time: row.start_time,
            end_time: row.end_time,
        };
        if(row.comment) item.description = row.comment;
        return[item];
    })
};

const saveWeek = () => {
    const payload = buildPayload();
    emit('save', payload);
}

const clearRow = (idx: number) => {
    rows.value[idx] = { ...empty_row };
}

watch(
    () => [timesheet_store.current_timesheet.start_day, timesheet_store.current_timesheet.shifts],
    () => {
        const dates = week_dates.value;
        rows.value = days.map((_, idx)=> {
            const shift = timesheet_store.current_timesheet.shifts.find(sh => sh.date === dates[idx]);
            return shift
                ? { type: shift.bank_type || '', start_time: shift.start_time || '', end_time: shift.end_time || '', comment: shift.description || '', is_approved: shift.is_approved} 
                : { type: '', start_time: '', end_time: '', comment: '', is_approved: false };
        });
    },
    { deep: true, immediate: true }
);

</script>

<template >
    <q-card class="q-pa-md q-ma-md">
        <q-dialog
            v-model="show_comment"
            transition-show="fade"
            transition-hide="fade"
            persistent
        >
            <TimesheetShiftComment
                :comment-string="selected_row?.comment ?? ''"
                @click-save="setComment"
                @click-close="show_comment = false"
            />
        </q-dialog>
        <q-form autofocus class="q-ml-xl">
            <TimesheetNavigation 
                :is-disabled="timesheet_store.is_loading"
                :is-previous-limit="is_calendar_limit"
                @date-selected="onDateSelected"
                @pressed-previous-button="timesheet_api.previous_week()"
                @pressed-current-button="timesheet_api.getCurrentWeekTimesheetOverview()"
                @pressed-next-button="timesheet_api.next_week()"
            />
            <div v-for="row, index in rows" :key="index" class="row q-gutter-sm q-mb-sm">
                <span class="text-weight-bold text-primary col-1">{{ days[index] }}</span>
                <q-select
                    v-model="row.type"
                    :options="shift_type"
                    :readonly="row.is_approved" 
                    class="col-2"
                    label="Type de Quart"
                    dense
                    filled
                    color="primary"
                    standout="bg-primary text-white"
                    options-dense
                    map-options    
                    hide-dropdown-icon                    
                />
                <q-input 
                    v-model="row.start_time"
                    :readonly="row.is_approved" 
                    class="col-2"
                    label="Entrée"
                    dense
                    filled
                    color="primary"
                    type="time"
                    step="300"
                    standout="bg-primary text-white"
                />
                <q-input 
                    v-model="row.end_time"
                    :readonly="row.is_approved" 
                    class="col-2"
                    label="Sortie"
                    dense
                    filled
                    clearable
                    color="primary"
                    type="time"
                    step="300"
                    standout="bg-primary text-white"
                />
                <q-btn 
                    :icon="row.comment.length > 0 ? 'announcement':'chat_bubble_outline'" 
                    :color="row.comment.length > 0 ? 'primary' : 'grey-8'"
                    :disable="row.is_approved"
                    flat
                    class="col-1"
                    @click="onClickComment(index)"
                />
                <q-btn
                    icon="cleaning_services"
                    flat
                    dense
                    class="q-pa-none q-ma-none justify-right"
                    :color="row.type.length || row.start_time.length || row.end_time.length || row.comment.length > 0 ? 'primary' : 'accent'"
                    @click="clearRow(index)"
                />
            </div>
        </q-form>
        <q-card-actions align="right">
            <q-btn
                color="primary"
                icon="save_alt"
                class="col-1"
                rounded
                push
                @click="saveWeek"        
            >
                <q-tooltip
                    anchor="top middle"
                    self="center middle"
                    class="bg-primary text-uppercase text-weight-bold"
                >Sauvegarder
                </q-tooltip>
            </q-btn>
        </q-card-actions>
    </q-card>
</template>