import {useEffect, useState} from "react";
import {TimeTrackingRecord, TimeTrackingService} from "../../../../../client";
import {dateWithoutTimezone, getDatesInMonth} from "../../../../../shared/lib/date.ts";
import {last} from "lodash";

const getDateBoundaries = (month: Date) => {
    return [getDatesInMonth(month)[0].toDate(), last(getDatesInMonth(month))?.toDate()]
}
const useWorkTableState = () => {
    const [month, setMonth] = useState<Date>(new Date(new Date().getFullYear(), new Date().getMonth(), 1));
    const [trackingRecords, setTrackingRecords] = useState<TimeTrackingRecord[]>([]);
    const [dateBoundaries, setDateBoundaries] = useState(getDateBoundaries(month));

    const refetch = async () => {
        return TimeTrackingService.getTimeTrackingRecords({
            requestBody: {
                date: dateWithoutTimezone(month),
                userIds: []
            }
        }).then((response) => setTrackingRecords(response.records));
    }

    useEffect(() => {
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        refetch().then(_ => {
            setDateBoundaries(getDateBoundaries(month));
        });

    }, [month])
    return {
        month,
        setMonth,
        refetch,
        trackingRecords,
        dateBoundaries
    }
}

export default useWorkTableState;