import React, { createContext, useState, useEffect, useContext } from 'react';
import authService from '../services/authService';

const AuthContext = createContext(null);

export const AuthProvider = ({ children }) => {
    const [user, setUser] = useState(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const params = new URLSearchParams(window.location.search);
        const urlToken = params.get('token');
        if (urlToken) {
            // Kiosk-Modus: Token aus URL → in localStorage speichern, URL bereinigen
            localStorage.setItem('token', urlToken);
            window.history.replaceState({}, '', window.location.pathname);
            authService.fetchUserFromToken(urlToken).then(userData => {
                if (userData) {
                    localStorage.setItem('user', JSON.stringify(userData));
                    setUser(userData);
                }
                setLoading(false);
            });
            return;
        }
        const storedUser = authService.getStoredUser();
        const token = authService.getToken();
        if (storedUser && token) {
            setUser(storedUser);
        }
        setLoading(false);
    }, []);

    const login = async (username, password) => {
        const data = await authService.login(username, password);
        setUser(data.user);
        return data;
    };

    // Called after Microsoft OAuth2 redirect with token in URL
    const loginWithToken = (token, userData) => {
        localStorage.setItem('token', token);
        localStorage.setItem('user', JSON.stringify(userData));
        setUser(userData);
    };

    const logout = async () => {
        await authService.logout();
        setUser(null);
    };

    const updateUser = (updatedUser) => {
        setUser(updatedUser);
        localStorage.setItem('user', JSON.stringify(updatedUser));
    };

    const hasRole = (allowedRoles) => {
        if (!user || !user.role_name) return false;
        return allowedRoles.includes(user.role_name);
    };

    const isSuperAdmin = () => hasRole(['super_admin']);
    const isAdmin = () => hasRole(['super_admin', 'admin']);
    const isTechniker = () => hasRole(['produktion']);
    const isSupport = () => hasRole(['super_admin', 'admin', 'support', 'bearbeiter']);
    const canViewLifecycle = () => hasRole(['super_admin', 'admin', 'support', 'hr_personal', 'buchhaltung']);
    const canModifyFidoKeys = () => hasRole(['super_admin', 'admin', 'bearbeiter']);
    const canViewFidoKeys = () => hasRole(['super_admin', 'admin', 'bearbeiter', 'benutzer']);
    const canViewTickets = () => !!user;
    const canModifyTickets = () => hasRole(['super_admin', 'admin', 'support']);

    const value = {
        user,
        loading,
        login,
        loginWithToken,
        logout,
        updateUser,
        hasRole,
        isSuperAdmin,
        isAdmin,
        isTechniker,
        isSupport,
        canViewLifecycle,
        canModifyFidoKeys,
        canViewFidoKeys,
        canViewTickets,
        canModifyTickets,
        isAuthenticated: !!user,
    };

    return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};

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