import React, { createContext, useContext, useState, useEffect } from 'react';
import { getSysParameter } from '../APIServices/SystemparameterApi';

const SystemParameterContext = createContext();

export const useSystemParameters = () => {
  const context = useContext(SystemParameterContext);
  if (!context) {
    throw new Error('useSystemParameters must be used within a SystemParameterProvider');
  }
  return context;
};

export const SystemParameterProvider = ({ children }) => {
  const [systemParameters, setSystemParameters] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchSystemParameters = async () => {
      try {
        const data = await getSysParameter(1); // Assuming 1 is the default ID for system parameters
        setSystemParameters(data);
        console.log("system parameters data ",data)
        setError(null);
      } catch (err) {
        setError('Failed to fetch system parameters');
        console.error('Error fetching system parameters:', err);
      } finally {
        setLoading(false);
      }
    };

    fetchSystemParameters();
  }, []);

  const value = {
    systemParameters,
    loading,
    error,
    refetch: async () => {
      setLoading(true);
      try {
        const data = await getSysParameter(1);
        setSystemParameters(data);
        setError(null);
      } catch (err) {
        setError('Failed to fetch system parameters');
        console.error('Error fetching system parameters:', err);
      } finally {
        setLoading(false);
      }
    }
  };

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