import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';

const API_BASE = process.env.REACT_APP_API_BASE || 'http://localhost:3001/api';

// Known BU teams — must match backend helpers/teams.js
const KNOWN_TEAMS = ['STEAM', 'ACCESS-ENG', 'ACCESS-OPS', 'INTELDEV'];

const AuthContext = createContext(null);

// Load admin scope from localStorage — returns array of selected teams
function loadAdminScope() {
    try {
        const saved = localStorage.getItem('admin_bu_scope');
        if (saved) {
            const parsed = JSON.parse(saved);
            if (Array.isArray(parsed)) return parsed;
        }
    } catch { /* ignore */ }
    // Default: null means "not yet initialized" — will be set to user's teams on first load
    return null;
}

function saveAdminScope(teams) {
    try {
        localStorage.setItem('admin_bu_scope', JSON.stringify(teams));
    } catch { /* ignore */ }
}

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

    // Admin scope — array of currently selected teams for filtering
    // null = not initialized yet (will default to user's teams after login)
    const [adminScope, setAdminScope] = useState(loadAdminScope);

    // Check if user is authenticated on mount
    const checkAuth = useCallback(async () => {
        try {
            const response = await fetch(`${API_BASE}/auth/me`, {
                credentials: 'include'
            });

            if (response.ok) {
                const data = await response.json();
                setUser(data.user);
                // Initialize admin scope to user's teams if not yet set
                if (adminScope === null && data.user?.teams?.length > 0) {
                    const initial = data.user.teams;
                    setAdminScope(initial);
                    saveAdminScope(initial);
                }
            } else {
                setUser(null);
            }
        } catch (err) {
            console.error('Auth check error:', err);
            setUser(null);
        } finally {
            setLoading(false);
        }
    }, []); // eslint-disable-line react-hooks/exhaustive-deps

    useEffect(() => {
        checkAuth();
    }, [checkAuth]);

    // Login function
    const login = async (username, password) => {
        setError(null);
        try {
            const response = await fetch(`${API_BASE}/auth/login`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include',
                body: JSON.stringify({ username, password })
            });

            const data = await response.json();

            if (!response.ok) {
                throw new Error(data.error || 'Login failed');
            }

            setUser(data.user);
            // Initialize scope to user's teams on login
            if (data.user?.teams?.length > 0 && adminScope === null) {
                const initial = data.user.teams;
                setAdminScope(initial);
                saveAdminScope(initial);
            }
            return { success: true };
        } catch (err) {
            setError(err.message);
            return { success: false, error: err.message };
        }
    };

    // Logout function
    const logout = async () => {
        try {
            await fetch(`${API_BASE}/auth/logout`, {
                method: 'POST',
                credentials: 'include'
            });
        } catch (err) {
            console.error('Logout error:', err);
        }
        setUser(null);
    };

    // Check if user belongs to one of the specified groups
    const isInGroup = (...groups) => user && groups.includes(user.group);

    // Check if user can perform write operations (Admin or Standard_User)
    const canWrite = () => isInGroup('Admin', 'Standard_User');

    // Check if user can delete a resource
    const canDelete = (resource) => {
        if (!user) return false;
        if (isInGroup('Admin')) return true;
        if (!isInGroup('Standard_User')) return false;
        return resource?.created_by === user.id;
    };

    // Check if user can export data
    const canExport = () => isInGroup('Admin', 'Standard_User', 'Leadership');

    // Check if user is admin
    const isAdmin = () => isInGroup('Admin');

    // -----------------------------------------------------------------------
    // Multi-BU tenancy helpers
    // -----------------------------------------------------------------------

    // Whether the user has any BU teams assigned
    const hasTeams = () => (user?.teams?.length ?? 0) > 0;

    // Whether the user is a member of a specific team
    const isTeamMember = (team) => {
        if (!user) return false;
        if (isInGroup('Admin')) {
            // Admin: check against current scope selection
            const scope = adminScope || [];
            return scope.length === 0 || scope.includes(team);
        }
        return (user.teams || []).includes(team);
    };

    // Set the admin scope to a specific set of teams
    const setAdminScopeTeams = (teams) => {
        setAdminScope(teams);
        saveAdminScope(teams);
    };

    // Returns the comma-joined teams string for API query params.
    // Empty string means "no filter" (show all).
    const getActiveTeamsParam = () => {
        if (!user) return '';

        if (isInGroup('Admin')) {
            const scope = adminScope || [];
            // If all teams selected or empty, no filter
            if (scope.length === 0 || scope.length === KNOWN_TEAMS.length) return '';
            return scope.join(',');
        }

        // Non-admin: always use their assigned teams
        const teams = user.teams || [];
        return teams.join(',');
    };

    // Returns the list of teams available for UI selectors (compliance team picker, etc.)
    const getAvailableTeams = () => {
        if (!user) return [];

        if (isInGroup('Admin')) {
            const scope = adminScope || [];
            // If all selected or empty, show all known teams
            if (scope.length === 0 || scope.length === KNOWN_TEAMS.length) return KNOWN_TEAMS;
            return scope;
        }

        return user.teams || [];
    };

    const value = {
        user,
        loading,
        error,
        login,
        logout,
        checkAuth,
        isInGroup,
        canWrite,
        canDelete,
        canExport,
        isAdmin,
        isAuthenticated: !!user,
        // Multi-BU tenancy
        hasTeams,
        isTeamMember,
        adminScope,
        setAdminScopeTeams,
        getActiveTeamsParam,
        getAvailableTeams,
        KNOWN_TEAMS,
    };

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

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