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

export const AdminSettingsContext = createContext();

export function useAdminSettings() {
  const context = useContext(AdminSettingsContext);
  if (context === undefined) {
    throw new Error('useAdminSettings must be used within an AdminSettingsProvider');
  }
  return context;
}

const DEFAULT_SETTINGS = {
  timezone: 'UTC',
  theme: 'light',
  colorPalette: 'default',
  enableArc: false,
  enablePayments: false,
  enableEmailRouting: false,
  requireMfa: false
};

export function AdminSettingsProvider({ children }) {
  const [settings, setSettings] = useState(() => {
    try {
      const saved = localStorage.getItem('adminSettings');
      return saved ? { ...DEFAULT_SETTINGS, ...JSON.parse(saved) } : DEFAULT_SETTINGS;
    } catch (e) {
      return DEFAULT_SETTINGS;
    }
  });

  const applyThemeToDocument = useCallback((theme, palette) => {
    const root = window.document.documentElement;
    
    // Reset classes
    root.classList.remove('light', 'dark');
    root.classList.remove('theme-default', 'theme-ocean', 'theme-forest', 'theme-sunset', 'theme-midnight');
    
    // Apply theme (light/dark)
    root.classList.add(theme);
    
    // Apply palette
    root.classList.add(`theme-${palette}`);
  }, []);

  useEffect(() => {
    applyThemeToDocument(settings.theme, settings.colorPalette);
  }, [settings.theme, settings.colorPalette, applyThemeToDocument]);

  // Persist settings whenever they change
  useEffect(() => {
    localStorage.setItem('adminSettings', JSON.stringify(settings));
  }, [settings]);

  const updateSettings = (newSettings) => {
    setSettings(prev => {
      const updated = { ...prev, ...newSettings };
      return updated;
    });
  };

  const updateSetting = (key, value) => {
    setSettings(prev => ({
      ...prev,
      [key]: value
    }));
  };

  const saveSettings = () => {
    localStorage.setItem('adminSettings', JSON.stringify(settings));
  };

  return (
    <AdminSettingsContext.Provider value={{
      settings,
      updateSettings,
      updateSetting,
      saveSettings,
      getTimezone: () => settings.timezone,
      getTheme: () => settings.theme,
      getColorPalette: () => settings.colorPalette
    }}>
      {children}
    </AdminSettingsContext.Provider>
  );
}
