import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
import { systemSettingsService } from '../services/systemSettingsService';
import type { SystemSettings } from '../services/systemSettingsService';

interface SystemSettingsContextType {
    settings: SystemSettings | null;
    isLoading: boolean;
    updateSettings: (newSettings: Partial<SystemSettings>) => Promise<void>;
}

const SystemSettingsContext = createContext<SystemSettingsContextType | undefined>(undefined);

export const SystemSettingsProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const [settings, setSettings] = useState<SystemSettings | null>(null);
    const [isLoading, setIsLoading] = useState(true);

    const fetchSettings = useCallback(async () => {
        try {
            const data = await systemSettingsService.getSettings();
            setSettings(data);
        } catch (error) {
            console.error('Failed to load system settings:', error);
            // Set defaults if fetch fails
            setSettings({
                settingsId: 'global',
                appName: 'GPI',
                appSubtitle: 'Gestão de Pintura Industrial'
            });
        } finally {
            setIsLoading(false);
        }
    }, []);

    const updateSettingsValue = async (newSettings: Partial<SystemSettings>) => {
        const updated = await systemSettingsService.updateSettings(newSettings);
        setSettings(updated);
    };

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

    return (
        <SystemSettingsContext.Provider value={{ settings, isLoading, updateSettings: updateSettingsValue }}>
            {children}
        </SystemSettingsContext.Provider>
    );
};

export const useSystemSettings = () => {
    const context = useContext(SystemSettingsContext);
    if (!context) {
        throw new Error('useSystemSettings must be used within a SystemSettingsProvider');
    }
    return context;
};
