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

const SettingsContext = createContext();

export const useSettings = () => useContext(SettingsContext);

export const SettingsProvider = ({ children }) => {
    // Theme State
    const [theme, setTheme] = useState(() => localStorage.getItem('theme') || 'light');

    // Dashboard Chart Type State ('bar' or 'line')
    const [chartType, setChartType] = useState(() => localStorage.getItem('chartType') || 'bar');

    // Docker Feature Config (Global Security Setting)
    const [dockerEnabled, setDockerEnabled] = useState(false);

    // Fetch Global Docker Config on mount
    useEffect(() => {
        const fetchConfig = async () => {
            try {
                const res = await fetch('/api/docker/config');
                if (res.ok) {
                    const data = await res.json();
                    setDockerEnabled(data.enabled);
                }
            } catch (e) {
                console.error('Failed to fetch docker config:', e);
            }
        };
        fetchConfig();
    }, []);

    // Network Interface Visibility State (Array of hidden interface names)
    const [hiddenInterfaces, setHiddenInterfaces] = useState(() => {
        const saved = localStorage.getItem('hiddenInterfaces');
        return saved !== null ? JSON.parse(saved) : [];
    });

    // Effects to save to localStorage and apply theme
    useEffect(() => {
        localStorage.setItem('theme', theme);
        document.documentElement.setAttribute('data-theme', theme);
    }, [theme]);

    useEffect(() => {
        localStorage.setItem('chartType', chartType);
    }, [chartType]);

    useEffect(() => {
        localStorage.setItem('hiddenInterfaces', JSON.stringify(hiddenInterfaces));
    }, [hiddenInterfaces]);

    // Sidebar Collapsed State (true/false)
    const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(() => {
        const saved = localStorage.getItem('isSidebarCollapsed');
        return saved !== null ? JSON.parse(saved) : false;
    });

    useEffect(() => {
        localStorage.setItem('isSidebarCollapsed', JSON.stringify(isSidebarCollapsed));
    }, [isSidebarCollapsed]);

    const toggleTheme = () => {
        setTheme(prev => prev === 'light' ? 'dark' : 'light');
    };

    const toggleInterfaceVisibility = (ifaceName) => {
        setHiddenInterfaces(prev => {
            if (prev.includes(ifaceName)) {
                return prev.filter(name => name !== ifaceName); // Show (remove from hidden)
            } else {
                return [...prev, ifaceName]; // Hide (add to hidden)
            }
        });
    };

    // Helper to refresh config manually (e.g. after Settings change)
    const refreshDockerConfig = async () => {
        try {
            const res = await fetch('/api/docker/config');
            if (res.ok) {
                const data = await res.json();
                setDockerEnabled(data.enabled);
            }
        } catch (e) { console.error(e); }
    };

    return (
        <SettingsContext.Provider value={{
            theme,
            toggleTheme,
            chartType,
            setChartType,
            dockerEnabled,
            refreshDockerConfig, // Expose for Settings page
            hiddenInterfaces,
            toggleInterfaceVisibility,
            isSidebarCollapsed,
            setIsSidebarCollapsed
        }}>
            {children}
        </SettingsContext.Provider>
    );
};
