import { useAuthContext } from "@/contexts/AuthContext";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import firestore from "@react-native-firebase/firestore";
import { IFeedback } from "@/contexts/FeedbackContext";
import { IBrainDump } from "@/contexts/DumpContext";

export const useCreateNote = () => {
  const { user: currentUser } = useAuthContext();
  const queryClients = useQueryClient();

  return useMutation({
    mutationKey: ["createNote"],
    mutationFn: async (note: Partial<IBrainDump>) => {
      try {
        const timestamp = firestore.FieldValue.serverTimestamp();
        
        if (note.id) {
          const snapshot = await firestore()
            .collection("BrainDumps")
            .where("id", "==", note.id)
            .get();

          if (!snapshot.empty) {
            const docId = snapshot.docs[0].id;
            await firestore()
              .collection("BrainDumps")
              .doc(docId)
              .set(
                {
                  ...note,
                  creatorId: currentUser?.uid,
                  updatedAt: timestamp
                },
                { merge: true }
              );
            return;
          }
        }
        
        const newDoc = firestore().collection("BrainDumps").doc();
        await newDoc.set({ 
          ...note, 
          id: newDoc.id, 
          creatorId: currentUser?.uid,
          updatedAt: timestamp,
          createdAt: timestamp
        });
      } catch (e) {
        console.error(e);
      }
    },
    onSuccess: () => {
      queryClients.invalidateQueries({queryKey: ["braindumps"]});
    },
  });
};

export const useCreateNotesFromProvider = () => {
  const { user: currentUser } = useAuthContext();
  const queryClient = useQueryClient();

  return useMutation({
    mutationKey: ["createNotesFromProvider"],
    mutationFn: async (noteDataArray: Partial<IFeedback>[]) => {
      try {
        const promises = noteDataArray.map(async (noteData) => {
          console.log("Processing NoteData: ", noteData);

          const snapshot = await firestore()
            .collection("BrainDumps")
            .where("id", "==", noteData.id)
            .get();

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

        await Promise.all(promises);
      } catch (e) {
        console.error("Error creating/updating braindumps: ", e);
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({queryKey: ["braindumps"]});
    },
  });
};
