import { computed, ref } from 'vue';
import { defineStore } from 'pinia';
import { unwrapAndClone } from 'src/utils/unwrap-and-clone';
import { timesheetApprovalService } from 'src/modules/timesheet-approval/services/timesheet-approval-service';
import { timesheetService } from 'src/modules/timesheets/services/timesheet-service';
import type { TimesheetOverview } from "src/modules/timesheet-approval/models/timesheet-overview.models";
import type { PayPeriod } from 'src/modules/shared/models/pay-period.models';
import type { Timesheet } from 'src/modules/timesheets/models/timesheet.models';
import type { TimesheetApprovalCSVReportFilters } from 'src/modules/timesheet-approval/models/timesheet-approval-csv-report.models';


export const useTimesheetStore = defineStore('timesheet', () => {
    const is_loading = ref<boolean>(false);
    const pay_period = ref<PayPeriod>();
    const timesheets = ref<Timesheet[]>([]);
    const all_current_shifts = computed(() => timesheets.value.flatMap(week => week.days.flatMap(day => day.shifts)) ?? []);
    const initial_timesheets = ref<Timesheet[]>([]);
    
    const pay_period_overviews = ref<TimesheetOverview[]>([]);
    
    const is_details_dialog_open = ref(false);
    const selected_employee_name = ref<string>();
    const current_pay_period_overview = ref<TimesheetOverview>();
    const search_filter = ref<string | number | null>('');
    const is_approval_grid_mode = ref<boolean>(true);
    const pay_period_report = ref();

    const getPayPeriodByDateOrYearAndNumber = async (date?: string): Promise<boolean> => {
        try {
            if (date !== undefined) {
                pay_period.value = await timesheetService.getPayPeriodByDate(date);
            } else if (pay_period.value !== undefined) {
                pay_period.value = await timesheetService.getPayPeriodByYearAndPeriodNumber(pay_period.value.pay_year, pay_period.value.pay_period_no);
            } else return false;

            return true;
        } catch (error) {
            console.error('Could not get current pay period: ', error);
            pay_period.value = undefined;
            pay_period_overviews.value = [];
            //TODO: More in-depth error-handling here

            return false;
        }
    };

    const getTimesheetOverviews = async (): Promise<boolean> => {
        is_loading.value = true;

        try {
            if (pay_period.value === undefined) {
                is_loading.value = false;
                return false;
            }

            const response = await timesheetApprovalService.getPayPeriodOverviews(pay_period.value.pay_year, pay_period.value.pay_period_no);
            pay_period_overviews.value = response.employees_overview;
            is_loading.value = false;

            return true;
        } catch (error) {
            console.error('There was an error retrieving Employee Pay Period overviews: ', error);
            pay_period_overviews.value = [];
            // TODO: More in-depth error-handling here
            is_loading.value = false;

            return false;
        }
    };

    const getTimesheetsByOptionalEmployeeEmail = async (employee_email?: string) => {
        if (pay_period.value === undefined) return;
        console.log('pay period: ', pay_period.value);
        is_loading.value = true;
        let response;

        try {
            if (employee_email) {
                response = await timesheetService.getTimesheetsByPayPeriodAndOptionalEmail(pay_period.value.pay_year, pay_period.value.pay_period_no, employee_email);
            } else {
                response = await timesheetService.getTimesheetsByPayPeriodAndOptionalEmail(pay_period.value.pay_year, pay_period.value.pay_period_no);
            }

            selected_employee_name.value = response.employee_fullname;
            timesheets.value = response.timesheets;
            initial_timesheets.value = unwrapAndClone(timesheets.value);
            is_loading.value = false;
        } catch (error) {
            console.error('There was an error retrieving timesheet details for this employee: ', error);
            // TODO: More in-depth error-handling here
            timesheets.value = [];
            is_loading.value = false;
        }
    };

    const getPayPeriodReportByYearAndPeriodNumber = async (year: number, period_number: number, report_filters?: TimesheetApprovalCSVReportFilters) => {
        try {
            const response = await timesheetApprovalService.getPayPeriodReportByYearAndPeriodNumber(
                year,
                period_number,
                report_filters
            );
            pay_period_report.value = response;
            return true;
        } catch (error) {
            console.error('There was an error retrieving the report CSV: ', error);
            // TODO: More in-depth error-handling here
        }

        return false;
    };

    return {
        is_loading,
        is_approval_grid_mode,
        is_details_dialog_open,
        search_filter,
        pay_period,
        pay_period_overviews,
        current_pay_period_overview,
        selected_employee_name,
        timesheets,
        all_current_shifts,
        initial_timesheets,
        getPayPeriodByDateOrYearAndNumber,
        getTimesheetOverviews,
        getTimesheetsByOptionalEmployeeEmail,
        getPayPeriodReportByYearAndPeriodNumber,
    };
});