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

interface Config {
    classes: Record<string, string>;
    markable: string[];
    default: string[];
    immutable: string[];
    allowClasses: string[];
}

interface RegisterMarkConfigProviderProps {
    children: React.ReactNode;
}

const RegisterMarkConfigContext = createContext<Config | null>(null);

// Custom hook to use the configuration context
export const useRegisterMarkConfig = () => {
    return useContext(RegisterMarkConfigContext);
};

// Provider component
export const RegisterMarkConfigProvider: React.FC<RegisterMarkConfigProviderProps> = ({ children }) => {
    const [config, setConfig] = useState<Config | null>(null);

    useEffect(() => {
        const fetchConfig = async () => {
            try {
                const response = await fetch('/api/cedar/v1/registermarks/uiconfig'); // Replace with your endpoint
                if (!response.ok) {
                    throw new Error(`Failed to fetch config: ${response.statusText}`);
                }
                const data: Config = await response.json();
                setConfig(data);
            } catch (error) {
                console.error("Error fetching configuration:", error);
            }
        };

        fetchConfig();
    }, []);

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