import React, { createContext, useContext, useState, useEffect } from 'react';
import useConfig from '../hooks/useConfig';

const ConfigContext = createContext();

export const useConfigContext = () => {
  const context = useContext(ConfigContext);
  if (!context) {
    throw new Error('useConfigContext must be used within ConfigProvider');
  }
  return context;
};

export const ConfigProvider = ({ children }) => {
  const { config, loading, error } = useConfig();
  const [userTypes, setUserTypes] = useState({});
  const [userTypeLabels, setUserTypeLabels] = useState({});
  const [rules, setRules] = useState([]);
  const [sections, setSections] = useState([]);
  const [logo, setLogo] = useState(null);
  const [appName, setAppName] = useState('');

  useEffect(() => {
    if (config) {
      const types = {};
      const labels = {};
      config.userTypes.forEach(type => {
        types[type.code] = type.code;
        labels[type.code] = type.label;
      });
      setUserTypes(types);
      setUserTypeLabels(labels);
      setRules(config.rules || []);
      setSections(config.sections || []);
      setLogo(config.logo || null);
      setAppName(config.appName || '');
    }
  }, [config]);

  const value = {
    config,
    loading,
    error,
    userTypes,
    userTypeLabels,
    rules,
    sections,
    logo,
    appName
  };

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