import { useQuery } from "react-query";
import firestore from "@react-native-firebase/firestore";
import { useAuthContext } from "@/contexts/AuthContext";
import { useAtomValue } from "jotai";
import { isFamilyViewAtom } from "@/components/pages/calendar/atoms";
import { colorMap } from "@/constants/colorMap";

export const useGetEvents = () => {
    const { user, profileData } = useAuthContext();
    const isFamilyView = useAtomValue(isFamilyViewAtom);

    return useQuery({
        queryKey: ["events", user?.uid, isFamilyView],
        queryFn: async () => {
            const db = firestore();
            const userId = user?.uid;
            const familyId = profileData?.familyId;

            let allEvents = [];

            // If family view is active, include family, creator, and attendee events
            if (isFamilyView) {
                const familyQuery = db.collection("Events").where("familyID", "==", familyId);
                const creatorQuery = db.collection("Events").where("creatorId", "==", userId);
                const attendeeQuery = db.collection("Events").where("attendees", "array-contains", userId);

                const [familySnapshot, creatorSnapshot, attendeeSnapshot] = await Promise.all([
                    familyQuery.get(),
                    creatorQuery.get(),
                    attendeeQuery.get(),
                ]);

                // Collect all events
                const familyEvents = familySnapshot.docs.map(doc => doc.data());
                const creatorEvents = creatorSnapshot.docs.map(doc => doc.data());
                const attendeeEvents = attendeeSnapshot.docs.map(doc => doc.data());

                allEvents = [...familyEvents, ...creatorEvents, ...attendeeEvents];
            } else {
                // Only include creator and attendee events when family view is off
                const creatorQuery = db.collection("Events").where("creatorId", "==", userId);
                const attendeeQuery = db.collection("Events").where("attendees", "array-contains", userId);

                const [creatorSnapshot, attendeeSnapshot] = await Promise.all([
                    creatorQuery.get(),
                    attendeeQuery.get(),
                ]);

                const creatorEvents = creatorSnapshot.docs.map(doc => doc.data());
                const attendeeEvents = attendeeSnapshot.docs.map(doc => doc.data());

                allEvents = [...creatorEvents, ...attendeeEvents];
            }

            // Use a Map to ensure uniqueness only for events with IDs
            const uniqueEventsMap = new Map();
            allEvents.forEach(event => {
                if (event.id) {
                    uniqueEventsMap.set(event.id, event); // Ensure uniqueness for events with IDs
                } else {
                    uniqueEventsMap.set(Math.random().toString(36), event); // Generate a temp key for events without ID
                }
            });
            const uniqueEvents = Array.from(uniqueEventsMap.values());

            // Filter out private events unless the user is the creator
            const filteredEvents = uniqueEvents.filter(event => {
                if (event.private) {
                    return event.creatorId === userId;
                }
                return true;
            });

            // Attach event colors and return the final list of events
            return await Promise.all(
                filteredEvents.map(async (event) => {
                    const profileSnapshot = await db
                        .collection("Profiles")
                        .doc(event.creatorId)
                        .get();

                    const profileData = profileSnapshot.data();
                    const eventColor = profileData?.eventColor || colorMap.pink;

                    return {
                        id: event.id || Math.random().toString(36).substr(2, 9), // Generate temp ID if missing
                        title: event.title,
                        start: new Date(event.startDate.seconds * 1000),
                        end: new Date(event.endDate.seconds * 1000),
                        hideHours: event.allDay,
                        eventColor,
                        notes: event.notes,
                    };
                })
            );
        },
        staleTime: Infinity,
        cacheTime: Infinity,
    });
};