import { createContext, useContext, useState, useEffect, type ReactNode } from 'react';
import { apiClient } from '../api/client';
import { useAuth } from '../auth/AuthContext';

export interface ModuleState {
    active: boolean;
    type: 'dev' | 'sub' | 'demo' | null;
    expiry: string | null;
}

interface SystemContextType {
    modules: Record<string, ModuleState>;
    refreshModules: () => Promise<void>;
    isLoading: boolean;
}

const SystemContext = createContext<SystemContextType | null>(null);

export function SystemProvider({ children }: { children: ReactNode }) {
    const [modules, setModules] = useState<Record<string, ModuleState>>({});
    const [isLoading, setIsLoading] = useState(true);
    const { isAuthenticated } = useAuth(); // Only load if authenticated

    const refreshModules = async () => {
        try {
            const response = await apiClient.get('/system/modules');
            if (response.data.modules) {
                setModules(response.data.modules);
            } else {
                // Fallback or assume old format (unsafe with new backend)
                // Better to assume new format based on my changes
                setModules(response.data.modules || response.data);
            }
        } catch (error) {
            console.error('Failed to load system modules:', error);
        } finally {
            setIsLoading(false);
        }
    };

    useEffect(() => {
        if (isAuthenticated) {
            refreshModules();
        } else {
            setModules({});
            setIsLoading(false);
        }
    }, [isAuthenticated]);

    return (
        <SystemContext.Provider value={{ modules, refreshModules, isLoading }}>
            {children}
        </SystemContext.Provider>
    );
}

export function useSystem() {
    const context = useContext(SystemContext);
    if (!context) {
        throw new Error('useSystem must be used within a SystemProvider');
    }
    return context;
}
