import {useAuthContext} from "@/contexts/AuthContext";
import {useMutation, useQueryClient} from "@tanstack/react-query";
import firestore from "@react-native-firebase/firestore";
import {EventData} from "@/hooks/firebase/types/eventData";
import {useAtomValue} from "jotai";
import {isFamilyViewAtom} from "@/components/pages/calendar/atoms";

export const useCreateEvent = () => {
    const {user: currentUser, profileData} = useAuthContext();
    const queryClient = useQueryClient();

    return useMutation({
        mutationKey: ["createEvent"],
        mutationFn: async (eventData: Partial<EventData>) => {
            const newDoc = firestore().collection('Events').doc();
            await firestore()
                .collection("Events")
                .add({
                    ...eventData,
                    id: newDoc.id,
                    creatorId: currentUser?.uid,
                    familyId: profileData?.familyId
                });
        },
        onMutate: async (newEvent) => {
            await queryClient.cancelQueries({
                queryKey: ["events", currentUser?.uid]
            });

            const formattedEvent = {
                ...newEvent,
                start: newEvent.startDate,
                end: newEvent.endDate,
                id: Date.now().toString(),
                creatorId: currentUser?.uid,
                familyId: profileData?.familyId,
                eventColor: profileData?.eventColor,
                hideHours: newEvent.allDay,
            };

            ["false", "true"].forEach(viewState => {
                const queryKey = ["events", currentUser?.uid, viewState === "true"];
                const previousData = queryClient.getQueryData(queryKey) as any[] || [];
                queryClient.setQueryData(queryKey, [...previousData, formattedEvent]);
            });
        },
        onSettled: () => {
            if (profileData?.familyId) {
                firestore()
                    .collection("Households")
                    .where("familyId", "==", profileData.familyId)
                    .get()
                    .then(snapshot => {
                        snapshot.docs.forEach(doc => {
                            doc.ref.update({
                                lastSyncTimestamp: firestore.FieldValue.serverTimestamp()
                            });
                        });
                    });
            }
        }
    });
};

export const useCreateEventsFromProvider = () => {
    const {user: currentUser, profileData} = useAuthContext();
    const queryClient = useQueryClient();

    return useMutation({
        mutationKey: ["createEventsFromProvider"],
        mutationFn: async (eventDataArray: Partial<EventData>[]) => {
            const promises = eventDataArray.map(async (eventData) => {
                const snapshot = await firestore()
                    .collection("Events")
                    .where("id", "==", eventData.id)
                    .get();

                if (snapshot.empty) {
                    return firestore()
                        .collection("Events")
                        .add({...eventData, creatorId: currentUser?.uid});
                }
                const docId = snapshot.docs[0].id;
                return firestore()
                    .collection("Events")
                    .doc(docId)
                    .set({...eventData, creatorId: currentUser?.uid}, {merge: true});
            });

            await Promise.all(promises);
        },
        onMutate: async (newEvents) => {
            await queryClient.cancelQueries({queryKey: ["events", currentUser?.uid]});

            const previousPersonalEvents = queryClient.getQueryData(["events", currentUser?.uid, false]);
            const previousFamilyEvents = queryClient.getQueryData(["events", currentUser?.uid, true]);

            const formattedEvents = newEvents.map(event => ({
                ...event,
                start: new Date(event.startDate.seconds * 1000),
                end: new Date(event.endDate.seconds * 1000),
                hideHours: event.allDay,
                eventColor: profileData?.eventColor,
                creatorId: currentUser?.uid,
                familyId: profileData?.familyId
            }));

            const updateQueryData = (old: any[] = []) => [...old, ...formattedEvents];

            queryClient.setQueryData(["events", currentUser?.uid, false], updateQueryData);
            queryClient.setQueryData(["events", currentUser?.uid, true], updateQueryData);

            return {previousPersonalEvents, previousFamilyEvents};
        },
        onError: (err, newEvents, context) => {
            queryClient.setQueryData(["events", currentUser?.uid, false], context?.previousPersonalEvents);
            queryClient.setQueryData(["events", currentUser?.uid, true], context?.previousFamilyEvents);
        },
        onSettled: () => {
            if (profileData?.familyId) {
                firestore()
                    .collection("Households")
                    .where("familyId", "==", profileData.familyId)
                    .get()
                    .then(snapshot => {
                        snapshot.docs.forEach(doc => {
                            doc.ref.update({
                                lastSyncTimestamp: firestore.FieldValue.serverTimestamp()
                            });
                        });
                    });
            }
        }
    })
}