import {useMutation} from "@tanstack/react-query";
import auth from "@react-native-firebase/auth";
import firestore from "@react-native-firebase/firestore";
import {ProfileType, useAuthContext} from "@/contexts/AuthContext";
import {useSetUserData} from "./useSetUserData";
import {uuidv4} from "@firebase/util";
import * as Localization from "expo-localization";

export const useSignUp = () => {
    const {setRedirectOverride} = useAuthContext();
    const {mutateAsync: setUserData} = useSetUserData();

    const createHouseholdIfNeeded = async (familyId: string, lastName: string) => {
        try {
            const householdRef = firestore().collection("Households");
            const snapshot = await householdRef.where("familyId", "==", familyId).get();

            if (snapshot.empty) {
                await householdRef.add({
                    familyId,
                    name: lastName
                });
            }
        } catch (error) {
            console.error("Error creating household:", error);
            throw error;
        }
    };

    return useMutation({
        mutationKey: ["signUp"],
        mutationFn: async ({
            email,
            password,
            firstName,
            lastName,
            birthday
        }: {
            email: string;
            password: string;
            firstName: string;
            lastName: string;
            birthday: Date;
        }) => {
            setRedirectOverride(true);
            const familyId = uuidv4();

            await auth()
                .createUserWithEmailAndPassword(email, password)
                .then(async (res) => {
                    try {
                        await setUserData({
                            newUserData: {
                                userType: ProfileType.PARENT,
                                firstName: firstName,
                                lastName: lastName,
                                familyId: familyId,
                                timeZone: Localization.getCalendars()[0].timeZone,
                                birthday: birthday
                            },
                            customUser: res.user,
                        });

                        await createHouseholdIfNeeded(familyId, lastName);
                    } catch (error) {
                        console.error(error);
                    }
                });
        },
    });
};