import React, { createContext, useContext, useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';

const AuthContext = createContext();

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

    const login = async (credentials, rememberMe, login) => {
        try {
            const response = await fetch('http://127.0.0.1:5001/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(credentials),
            });
            const data = await response.json();
            if (data.success) {
                setUser(credentials.username);
                localStorage.setItem('user', JSON.stringify(credentials));
                if (rememberMe) {
                    localStorage.setItem('rememberMe', 'true');
                } else {
                    localStorage.setItem('rememberMe', 'false');
                }
                if (login) {
                    navigate('/dashboard');
                }
                else {
                    return {"success": true, "message": "Authentication successful"};
                }
            } else {
                throw new Error('Login failed');
            }
        } catch (error) {
            console.error('Login error:', error);
        }
    };

    const logout = () => {
        if (!localStorage.getItem('rememberMe')) {
            localStorage.removeItem('user');
        }
        navigate('/');
    };

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

export const useAuth = () => useContext(AuthContext);