import React, { createContext, useContext, useEffect, useState } from 'react';
import { onAuthStateChanged, signOut } from 'firebase/auth';
import { auth } from '../firebaseConfig';

const AuthContext = createContext();

export const useAuth = () => {
    const context = useContext(AuthContext);
    if (!context) {
        throw new Error('useAuth must be used within an AuthProvider');
    }
    return context;
};

export const AuthProvider = ({ children }) => {
    const [currentUser, setCurrentUser] = useState(null);
    const [loading, setLoading] = useState(true);
    const [authToken, setAuthToken] = useState(null);

    useEffect(() => {
        const unsubscribe = onAuthStateChanged(auth, async (user) => {
            setCurrentUser(user);
            
            if (user) {
                try {
                    const token = await user.getIdToken();
                    setAuthToken(token);
                    
                    localStorage.setItem('authToken', token);
                } catch (error) {
                    console.error('Error getting auth token:', error);
                    setAuthToken(null);
                }
            } else {
                setAuthToken(null);
                localStorage.removeItem('authToken');
            }
            
            setLoading(false);
        });

        return unsubscribe;
    }, []);

    const logout = async () => {
        try {
            await signOut(auth);
            setAuthToken(null);
            localStorage.removeItem('authToken');
        } catch (error) {
            console.error('Error signing out:', error);
        }
    };

    const value = {
        currentUser,
        authToken,
        logout,
        loading
    };

    return (
        <AuthContext.Provider value={value}>
            {!loading && children}
        </AuthContext.Provider>
    );
};