import React, {memo} from 'react';
import {Calendar} from "react-native-big-calendar";
import {StyleSheet} from "react-native";
import {useGetEvents} from "@/hooks/firebase/useGetEvents";
import {useAtom, useAtomValue, useSetAtom} from "jotai";
import {
    editVisibleAtom,
    eventForEditAtom,
    modeAtom,
    selectedDateAtom,
    selectedNewEventDateAtom
} from "@/components/pages/calendar/atoms";
import {useAuthContext} from "@/contexts/AuthContext";

interface EventCalendarProps {
    calendarHeight: number;
}

export const EventCalendar: React.FC<EventCalendarProps> = memo(({calendarHeight}) => {
    const {data: events} = useGetEvents();
    const {profileData} = useAuthContext()
    const [selectedDate, setSelectedDate] = useAtom(selectedDateAtom)
    const [mode, setMode] = useAtom(modeAtom)
    const setEditVisible = useSetAtom(editVisibleAtom)
    const setEventForEdit = useSetAtom(eventForEditAtom)
    const setSelectedNewEndDate = useSetAtom(selectedNewEventDateAtom)

    console.log("Events: ", events)

    return (
        <Calendar
            bodyContainerStyle={styles.calHeader}
            mode={mode}
            events={events ?? []}
            eventCellStyle={(event) => ({backgroundColor: event.eventColor})}
            onPressEvent={(event) => {
                setEditVisible(true);
                setEventForEdit(event);
            }}
            weekStartsOn={profileData?.firstDayOfWeek === "Mondays" ? 1 : 0}
            height={calendarHeight}
            activeDate={selectedDate}
            date={selectedDate}
            onPressCell={mode === "day" ? setSelectedNewEndDate: (date) => {
                setSelectedDate(date)
                setMode("day")
            }}
            headerContentStyle={mode === "day" ? styles.dayModeHeader : {}}
            onSwipeEnd={(date) => {
                setSelectedDate(date);
            }}
        />
    );
});

const styles = StyleSheet.create({
    segmentslblStyle: {
        fontSize: 12,
        fontFamily: "Manrope_600SemiBold",
    },
    calHeader: {
        borderWidth: 0,
    },
    dayModeHeader: {
        alignSelf: "flex-start",
        justifyContent: "space-between",
        alignContent: "center",
        width: 38,
        right: 42,
    },
});
