import { useCallback } from 'react';
import debounce from 'debounce';
import { useSetAtom } from 'jotai';
import {
    editVisibleAtom,
    eventForEditAtom,
    selectedNewEventDateAtom,
    selectedDateAtom,
} from '@/components/pages/calendar/atoms';
import {DateOrDateTime} from "@howljs/calendar-kit";

export const useCalendarControls = (events: any[]) => {
    const setEditVisible = useSetAtom(editVisibleAtom);
    const setEventForEdit = useSetAtom(eventForEditAtom);
    const setSelectedNewEndDate = useSetAtom(selectedNewEventDateAtom);
    const setSelectedDate = useSetAtom(selectedDateAtom);

    const handlePressEvent = useCallback((event: any) => {
        const foundEvent = events?.find(x => x.id === event.id);

        if (foundEvent) {
            const processedEvent = {
                ...foundEvent,
                startDate: foundEvent.startDate?.seconds ?
                    new Date(foundEvent.startDate.seconds * 1000) :
                    new Date(foundEvent.start),
                endDate: foundEvent.endDate?.seconds ?
                    new Date(foundEvent.endDate.seconds * 1000) :
                    new Date(foundEvent.end)
            };

            if (processedEvent.startDate instanceof Date &&
                processedEvent.endDate instanceof Date &&
                !isNaN(processedEvent.startDate.getTime()) &&
                !isNaN(processedEvent.endDate.getTime())) {
                setEditVisible(true);
                setEventForEdit(processedEvent);
            }
        }
    }, [events, setEditVisible, setEventForEdit]);


    const handlePressCell = useCallback((date: DateOrDateTime) => {
        const selectedDate = new Date(date.dateTime!);
        const minutes = selectedDate.getMinutes();

        selectedDate.setMinutes(minutes - (minutes % 30), 0, 0);

        setSelectedNewEndDate(selectedDate);
    }, [setSelectedNewEndDate]);

    const debouncedOnDateChanged = useCallback(
        debounce((date: string) => {
            setSelectedDate(new Date(date));
        }, 50),
        [setSelectedDate]
    );

    return {
        handlePressEvent,
        handlePressCell,
        debouncedOnDateChanged
    };
};