import React, {useCallback, useMemo, useRef} from "react";
import {useAuthContext} from "@/contexts/AuthContext";
import {useAtomValue} from "jotai";
import {modeAtom, selectedDateAtom, selectedUserAtom} from "@/components/pages/calendar/atoms";
import {useGetFamilyMembers} from "@/hooks/firebase/useGetFamilyMembers";
import {CalendarBody, CalendarContainer, CalendarHeader, CalendarKitHandle} from "@howljs/calendar-kit";
import {useGetEvents} from "@/hooks/firebase/useGetEvents";
import {useFormattedEvents} from "@/components/pages/calendar/useFormattedEvents";
import {useCalendarControls} from "@/components/pages/calendar/useCalendarControls";
import {EventCell} from "@/components/pages/calendar/EventCell";
import {isToday} from "date-fns";
import { View } from "react-native-ui-lib";

interface EventCalendarProps {
    calendarHeight: number;
    calendarWidth: number;
}

export const DetailedCalendar: React.FC<EventCalendarProps> = ({calendarHeight, calendarWidth}) => {
    const {profileData} = useAuthContext();
    const selectedDate = useAtomValue(selectedDateAtom);
    const mode = useAtomValue(modeAtom);
    const {data: familyMembers} = useGetFamilyMembers();
    const personalCalendarRef = useRef<CalendarKitHandle>(null);
    const familyCalendarRef = useRef<CalendarKitHandle>(null);
    const {data: events} = useGetEvents();
    const selectedUser = useAtomValue(selectedUserAtom);

    const {data: personalEvents} = useFormattedEvents(events ?? [], selectedDate, profileData?.uid);
    const {data: familyEvents} = useFormattedEvents(events ?? [], selectedDate, null);

    const {
        handlePressEvent,
        handlePressCell,
        debouncedOnDateChanged
    } = useCalendarControls(events ?? []);

    const numberOfDays = useMemo(() => {
        return mode === 'week' ? 7 : mode === '3days' ? 3 : 1;
    }, [mode]);

    const firstDay = useMemo(() => {
        return profileData?.firstDayOfWeek === "Mondays" ? 1 : 0;
    }, [profileData?.firstDayOfWeek]);

    const headerProps = useMemo(() => ({
        dayBarHeight: 60,
        headerBottomHeight: 20
    }), []);

    const bodyProps = useMemo(() => ({
        showNowIndicator: true,
        hourFormat: "h:mm a"
    }), []);

    const containerProps = useMemo(() => ({
        hourWidth: 70,
        allowPinchToZoom: true,
        useHaptic: true,
        scrollToNow: true,
        initialDate: selectedDate.toISOString(),
    }), [selectedDate]);

    const renderEvent = useCallback((event: any) => {
        const eventAttendees = familyMembers?.filter(member =>
            event?.attendees?.includes(member?.uid!)
        ) || [];

        return (
            <EventCell
                key={event.id}
                event={event}
                onPress={handlePressEvent}
                attendees={eventAttendees}
            />
        );
    }, [familyMembers, handlePressEvent]);

    return (
        <View style={{ position: 'relative', width: calendarWidth, height: calendarHeight }}>
            <View
                style={{
                    position: 'absolute',
                    width: '100%',
                    height: '100%',
                    opacity: selectedUser?.uid === profileData?.uid ? 1 : 0,
                    pointerEvents: selectedUser?.uid === profileData?.uid ? 'auto' : 'none',
                    // transition: 'opacity 0.2s ease-in-out'
                }}
            >
                <CalendarContainer
                    ref={personalCalendarRef}
                    {...containerProps}
                    numberOfDays={numberOfDays}
                    calendarWidth={calendarWidth}
                    onDateChanged={debouncedOnDateChanged}
                    firstDay={firstDay}
                    events={personalEvents ?? []}
                    onPressEvent={handlePressEvent}
                    onPressBackground={handlePressCell}
                >
                    <CalendarHeader {...headerProps} />
                    <CalendarBody
                        {...bodyProps}
                        renderEvent={renderEvent}
                    />
                    <View marginB-45/>
                </CalendarContainer>
            </View>

            <View
                style={{
                    position: 'absolute',
                    width: '100%',
                    height: '100%',
                    opacity: selectedUser?.uid === profileData?.uid ? 0 : 1,
                    pointerEvents: selectedUser?.uid === profileData?.uid ? 'none' : 'auto',
                    // transition: 'opacity 0.2s ease-in-out'
                }}
            >
                <CalendarContainer
                    ref={familyCalendarRef}
                    {...containerProps}
                    numberOfDays={numberOfDays}
                    calendarWidth={calendarWidth}
                    onDateChanged={debouncedOnDateChanged}
                    firstDay={firstDay}
                    events={familyEvents ?? []}
                    onPressEvent={handlePressEvent}
                    onPressBackground={handlePressCell}
                >
                    <CalendarHeader {...headerProps} />
                    <CalendarBody
                        {...bodyProps}
                        renderEvent={renderEvent}
                    />
                    <View marginB-45/>
                </CalendarContainer>
            </View>
        </View>
    );
};

