import { useDispatch } from "react-redux";
import { notification } from "antd";
import { setError, setUser } from "../../../Redux/Slices/authSlice.js";
import { useLoginMutation } from "../../../Api/authApi.js";
import { checkAuth } from "../../../Redux/Slices/authSlice.js";

const useLoginPage = () => {
    const dispatch = useDispatch();
    const [loginUser, { isLoading }] = useLoginMutation();

    const onFinish = async (loginData) => {
        try {
            const response = await loginUser(loginData).unwrap();
            const token = response.access_token || response.token;
            if (!token) {
                throw new Error("Сервер не вернул токен авторизации");
            }
            localStorage.setItem("access_token", token);
            dispatch(setUser({ token }));

            await dispatch(checkAuth()).unwrap();
        } catch (error) {
            const errorMessage = error?.data?.detail || "Не удалось войти. Проверьте логин и пароль.";
            console.error(error);
            dispatch(setError(errorMessage));
            notification.error({
                message: "Ошибка при входе",
                description: errorMessage,
                placement: "topRight",
            });
        }
    };

    return {
        onFinish,
        isLoading,
    };
};

export default useLoginPage;