import { useEffect, useRef } from "react";
import { useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { Grid, 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 { useBreakpoint } = Grid;

const useLoginPage = () => {
    const navigate = useNavigate();
    const dispatch = useDispatch();
    const [loginUser, { isLoading }] = useLoginMutation();
    const { user, userData } = useSelector((state) => state.auth);
    const screens = useBreakpoint();
    const hasRedirected = useRef(false);

    const containerStyle = {
        minHeight: "100vh",
    };

    const formContainerStyle = {
        padding: screens.xs ? 10 : 20,
        border: "1px solid #ddd",
        borderRadius: 8,
        textAlign: "center",
    };

    const titleStyle = {
        textAlign: "center",
        marginBottom: 20,
    };

    const logoStyle = {
        width: 80,
        marginBottom: 10,
        borderRadius: 20,
        border: "1px solid #ddd",
    };

    const appNameStyle = {
        textAlign: "center",
        color: "#1890ff",
        marginBottom: 40,
    };

    const logoBlockStyle = {
        display: "flex",
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center",
    };

    const labels = {
        title: "Авторизация",
        loginPlaceholder: "Логин",
        passwordPlaceholder: "Пароль",
        submitButton: "Войти",
        loginRequired: "Пожалуйста, введите логин",
        passwordRequired: "Пожалуйста, введите пароль",
    };

    useEffect(() => {
        if (user && userData && !isLoading && !hasRedirected.current) {
            hasRedirected.current = true;
            navigate("/");
        }
        document.title = labels.title;
    }, [user, userData, isLoading, navigate]);

    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 {
        containerStyle,
        formContainerStyle,
        titleStyle,
        logoStyle,
        appNameStyle,
        labels,
        logoBlockStyle,
        onFinish,
        isLoading,
    };
};

export default useLoginPage;