import React, { useState, createContext, useContext } from 'react';
import { User } from '@repo/shared-types';

const SESSION_KEY = 'edtech_admin_token';
const USER_KEY = 'edtech_admin_user';

interface AuthContextType {
    token: string | null;
    user: User | null;
    login: (token: string, user: User) => void;
    logout: () => void;
}

export const AuthContext = createContext<AuthContextType>({ 
    token: null, 
    user: null,
    login: () => {}, 
    logout: () => {} 
});

export function AuthProvider({ children }: { children: React.ReactNode }) {
    const [token, setToken] = useState<string | null>(() => sessionStorage.getItem(SESSION_KEY));
    const [user, setUser] = useState<User | null>(() => {
        const saved = sessionStorage.getItem(USER_KEY);
        return saved ? JSON.parse(saved) : null;
    });
    
    const login = (t: string, u: User) => { 
        sessionStorage.setItem(SESSION_KEY, t); 
        sessionStorage.setItem(USER_KEY, JSON.stringify(u));
        setToken(t); 
        setUser(u);
    };
    
    const logout = () => { 
        sessionStorage.removeItem(SESSION_KEY); 
        sessionStorage.removeItem(USER_KEY);
        setToken(null); 
        setUser(null);
    };
    
    return (
        <AuthContext.Provider value={{ token, user, login, logout }}>
            {children}
        </AuthContext.Provider>
    );
}

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