import {createContext, useState, useContext, useEffect} from "react";
import PropTypes from "prop-types";
import loginUser from "./api/auth/loginRequest.jsx";
import {Spin} from "antd";
import {useNavigate} from "react-router-dom";
import createApi from "./core/axiosConfig.jsx";

const AuthContext = createContext(undefined);

const AuthProvider = ({children}) => {
    const [user, setUser] = useState(null);
    const [isLoading, setIsLoading] = useState(true);
    const navigate = useNavigate();

    useEffect(() => {
        const token = localStorage.getItem("access_token");
        if (token) {
            setUser({token});
        }
        setIsLoading(false);
    }, []);


    const login = async (loginData) => {
        try {
            const token = await loginUser(loginData, api);
            localStorage.setItem("access_token", token);
            setUser({token});
        } catch (error) {
            console.error("Login failed", error);
            throw error;
        }
    };

    const logoutAndRedirect = () => {
        localStorage.removeItem("access_token");
        setUser(null);
        navigate("/login");
    };

    const logout = () => {
        localStorage.removeItem("access_token");
        setUser(null);
    };

    if (isLoading) {
        return <Spin/>;
    }

    const api = createApi(logoutAndRedirect);

    return (
        <AuthContext.Provider value={{user, login, logout, logoutAndRedirect, api}}>
            {children}
        </AuthContext.Provider>
    );
};

AuthProvider.propTypes = {
    children: PropTypes.node.isRequired,
};

const useAuth = () => {
    return useContext(AuthContext);
};

export {useAuth, AuthProvider};