import { useState } from "react";
import { useForm } from "react-hook-form"
import { ApiRequestStatus } from "../../common/const/api_request_states";
import { useDataContext } from "../../common/contexts/data_context";
import { router } from "expo-router";

interface ChangePasswordValues {
    oldPassword: string;
    newPassword: string;
    confirmPassword: string;
}

export const useChangePassword = () => {
    const { control, handleSubmit, setError } = useForm<ChangePasswordValues>();
    const [status, setStatus] = useState<ApiRequestStatus>(ApiRequestStatus.IDLE);
    const { profileRepository } = useDataContext();

    const setLoading = async () => {
        setStatus(ApiRequestStatus.LOADING);
    }

    const request = async (values: ChangePasswordValues) => {
        await setLoading();
        try {
            await profileRepository!.changePassword(values.oldPassword, values.newPassword);
            setStatus(ApiRequestStatus.SUCCESS);
            router.back();
        } catch (error) {
            setError("oldPassword", { type: "manual", message: "The current password is incorrect" });
            setStatus(ApiRequestStatus.ERROR);
        }
    }

    const onSubmit = async () => {
        await handleSubmit(async (data) => {
            await request(data);
        })();
    }
    return { control, onSubmit, status };
}