import {useState} from "react";
import * as ImagePicker from "expo-image-picker";
import {useChangeProfilePicture} from "@/hooks/firebase/useChangeProfilePicture";
import {useUpdateUserData} from "@/hooks/firebase/useUpdateUserData";

export const useUploadProfilePicture = (customUserId?: string, existingPfp?: string) => {
    const [profileImage, setProfileImage] = useState<
        string | ImagePicker.ImagePickerAsset | null
    >(existingPfp || null);

    const [profileImageAsset, setProfileImageAsset] = useState<
        ImagePicker.ImagePickerAsset | null
    >(null);

    const {mutateAsync: updateUserData} = useUpdateUserData();
    const {mutateAsync: changeProfilePicture} = useChangeProfilePicture(customUserId);

    const pickImage = async () => {
        const permissionResult =
            await ImagePicker.requestMediaLibraryPermissionsAsync();
        if (!permissionResult.granted) {
            alert("Permission to access camera roll is required!");
            return;
        }

        const result = await ImagePicker.launchImageLibraryAsync({
            mediaTypes: ImagePicker.MediaTypeOptions.Images,
            allowsEditing: true,
            aspect: [1, 1],
            quality: 1,
        });

        if (!result.canceled) {
            setProfileImage(result.assets[0].uri);
            setProfileImageAsset(result.assets[0]);
            if (!customUserId) {
                await changeProfilePicture(result.assets[0]);
            }
        }
    };

    const handleClearImage = async () => {
        if (!customUserId) {
            await updateUserData({newUserData: {pfp: null}});
        }
        setProfileImage(null);
    };

    const pfpUri =
        profileImage && typeof profileImage === "object" && "uri" in profileImage
            ? profileImage.uri
            : profileImage;

    return {
        pfpUri,
        profileImage,
        profileImageAsset,
        handleClearImage,
        pickImage,
        changeProfilePicture
    }
}