import { useForm } from "react-hook-form"
import { useDataContext } from "../contexts/data_context";
import { useAuth } from "../contexts/auth_context";
import { router } from "expo-router";

interface SignUpForm {
    name: string;
    lastName: string;
    email: string;
    password: string;
    confirmPassword: string;
    dateOfBirth: string;
}

export const useSignUp = () => {
    const { control, setError, handleSubmit } = useForm<SignUpForm>();
    const { authRepository } = useDataContext();
    const { login } = useAuth();

    const validSubmit = async (data: SignUpForm) => {
        try {
            if (data.password !== data.confirmPassword) {
                setError("confirmPassword", { type: "manual", message: "Passwords don't match" });
                return;
            }
            const userToRegister = {
                name: data.name,
                lastName: data.lastName,
                email: data.email,
                password: data.password,
                confirmPassword: data.confirmPassword,
                birthdate: data.dateOfBirth
            }
            const { user, token } = await authRepository!.register(userToRegister);
            await login(user, token);
            router.replace("/(tabs)");
        } catch (error: any) {
            switch (error.response.status) {
                case 400:
                    setError("email", { type: "manual", message: "Email already in use" });
                    break;
                default:
                    console.log("Something went wrong");
                    break;
            }
        }
    }

    const invalidSubmit = (errors: any) => {
        console.log(errors);
    }

    const onSubmit = async () => {
        await handleSubmit(validSubmit, invalidSubmit)();
    }

    return { control, onSubmit };
}