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

export type LoginFormValues = {
    email: string;
    password: string;
}

export const useLoggin = () => {
    const { control, handleSubmit, formState: { errors }, setError } = useForm<LoginFormValues>();
    const { authRepository } = useDataContext();
    const { login } = useAuth();

    const validSubmit = async (data: LoginFormValues) => {
        try {
            const { user, token } = await authRepository!.login(data.email, data.password);
            await login(user, token);
            router.replace('/(tabs)');
        } catch (error: any) {
            switch (error.response.status) {
                case 401:
                    setError('email', { type: 'manual', message: 'Invalid email or password' });
                    setError('password', { type: 'manual', message: 'Invalid email or password' });
                    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 };
}