import { createContext, useContext } from '@wordpress/element';
import useSettings from '../hooks/useSettings';

/**
 * Context for managing settings data across components
 * Provides centralized access to settings state and operations
 */
const SettingsContext = createContext();

/**
 * Provider component that wraps components needing settings data
 * Should be placed at the root level of the admin interface
 *
 * @param {Object} props Component props
 * @param {React.ReactNode} props.children Child components
 * @returns {JSX.Element} Provider component
 */
export const SettingsProvider = ({ children }) => {
  const settingsData = useSettings();

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

/**
 * Custom hook to consume settings context
 * Provides access to settings state and operations
 *
 * @returns {Object} Settings data with state and operations
 * @returns {Object} return.settings - Current settings object
 * @returns {Function} return.updateSetting - Function to update a single setting
 * @returns {Function} return.saveSettings - Function to save settings to API
 * @returns {Function} return.saveApiConfiguration - Function to save API configuration to dedicated endpoint
 * @returns {Function} return.loadSettings - Function to reload settings from API
 * @returns {boolean} return.isLoading - Whether settings are currently loading
 * @returns {boolean} return.isSaving - Whether settings are currently saving
 * @returns {Function} return.clearNotice - Function to clear current notices
 */
export const useSettingsContext = () => {
  const context = useContext(SettingsContext);

  if (context === undefined) {
    throw new Error('useSettingsContext must be used within a SettingsProvider');
  }

  return context;
};

export default SettingsContext;
