import firestore from "@react-native-firebase/firestore";
import {FirebaseAuthTypes} from "@react-native-firebase/auth";
import {useMutation, useQueryClient} from "@tanstack/react-query";
import {useAuthContext} from "@/contexts/AuthContext";
import {UserProfile} from "@/hooks/firebase/types/profileTypes";
import {Alert} from "react-native";

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

    return useMutation({
        mutationKey: ["updateUserData"],
        mutationFn: async ({
                               newUserData,
                               customUser,
                           }: {
            newUserData: Partial<UserProfile>;
            customUser?: FirebaseAuthTypes.User;
        }) => {
            console.log("Mutation function called with data:", {newUserData, customUser});

            const user = currentUser ?? customUser;

            if (user) {
                console.log("Updating user data for UID:", user.uid);

                try {
                    const updatedUserData = Object.fromEntries(
                        Object.entries(newUserData).map(([key, value]) =>
                            [key, value === null ? firestore.FieldValue.delete() : value]
                        )
                    );

                    console.log("Updated user data with deletions:", updatedUserData);

                    await firestore()
                        .collection("Profiles")
                        .doc(user.uid)
                        .update(updatedUserData);

                    console.log("User data updated successfully, fetching updated profile...");

                    await refreshProfileData();

                    console.log("Profile data updated in context.");
                } catch (e) {
                    console.error("Error updating user data:", e);
                }
            } else {
                console.warn("No user found: currentUser and customUser are both undefined.");
            }
        },
        onSuccess: () => {
            queryClient.invalidateQueries({queryKey: ["events"]})
        },
    });
};

export const useSpendPoints = () => {
    const { user: currentUser } = useAuthContext();

    return useMutation({
        mutationKey: ["spendPoints"],
        mutationFn: async (pointsToSpend: number) => {
            const userRef = firestore().collection("Profiles").doc(currentUser?.uid);
            let userSnapshot = await userRef.get();
            let userData = userSnapshot.data() as UserProfile;

            if (!userData) return;

            const allTimePoints = userData.allTimePoints || 0;
            if (allTimePoints < pointsToSpend) {
                return;
            }

            await userRef.update({...userData,allTimePoints: allTimePoints - pointsToSpend,})

            Alert.alert("Success", `You spent ${pointsToSpend} points!`);
        },
    });
}