import {useMutation, useQueryClient} from "@tanstack/react-query";
import firestore from "@react-native-firebase/firestore";
import storage from "@react-native-firebase/storage";
import {useAuthContext} from "@/contexts/AuthContext";
import * as ImagePicker from "expo-image-picker";
import {Platform} from "react-native";

export const useChangeProfilePicture = (customUserId?: string) => {
    const queryClient = useQueryClient();
    const {user, refreshProfileData} = useAuthContext();

    return useMutation({
        mutationKey: ["changeProfilePicture"],
        mutationFn: async (profilePicture: ImagePicker.ImagePickerAsset) => {
            if (!profilePicture?.uri) {
                throw new Error("No image selected");
            }

            let imageUri = profilePicture.uri;

            console.log("Selected image URI:", imageUri);

            if (Platform.OS === 'ios' && !imageUri.startsWith('file://')) {
                imageUri = `file://${imageUri}`;
                console.log("Updated image URI for iOS:", imageUri);
            }

            const fileName = `profilePictures/${new Date().getTime()}_profile.jpg`;
            console.log("Firebase Storage file path:", fileName);

            try {
                const reference = storage().ref(fileName);

                console.log('Uploading image to Firebase Storage...');
                await reference.putFile(imageUri);
                console.log('Image uploaded successfully!');

                const downloadURL = await reference.getDownloadURL();
                console.log("Download URL:", downloadURL);

                if(!customUserId) {
                    await firestore()
                        .collection("Profiles")
                        .doc(user?.uid)
                        .update({pfp: downloadURL});
                } else {
                    await firestore()
                        .collection("Profiles")
                        .doc(customUserId)
                        .update({pfp: downloadURL});
                }

            } catch (e) {
                console.error("Error uploading profile picture:", e);
                throw e;
            }
        },
        onSuccess: () => {
            // Invalidate queries to refresh profile data
            if (!customUserId) {
                queryClient.invalidateQueries({queryKey: ["Profiles"]});
                refreshProfileData();
            } else {
                queryClient.invalidateQueries({queryKey: ["Profiles"]});
            }
        },
    });
};