import React, { createContext, useContext, useState, useEffect } from 'react';
import apiFetch from '@wordpress/api-fetch';

const SettingsContext = createContext();

export const useSettings = () => {
  const context = useContext(SettingsContext);
  if (!context) {
    throw new Error('useSettings must be used within a SettingsProvider');
  }
  return context;
};

export const SettingsProvider = ({ children }) => {
  const [settings, setSettings] = useState({});
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);

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

  const loadSettings = async () => {
    setIsLoading(true);
    setError(null);

    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/settings',
      });
      setSettings(response);
    } catch (err) {
      setError(err.message);
    } finally {
      setIsLoading(false);
    }
  };

  const updateSettings = async (newSettings) => {
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/settings',
        method: 'POST',
        data: newSettings,
      });

      if (response.success) {
        setSettings({ ...settings, ...newSettings });
        return { success: true };
      }

      return { success: false, message: response.message };
    } catch (err) {
      return { success: false, message: err.message };
    }
  };

  const getGroup = (groupKey) => {
    return settings[groupKey] || {};
  };

  const value = {
    settings,
    isLoading,
    error,
    updateSettings,
    getGroup,
    reload: loadSettings,
  };

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