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

interface SubscriptionEventsContextType {
  subscriptionVersion: number;
  notifySubscriptionChanged: () => void;
  subscribeToChanges: (callback: () => void) => () => void;
}

const SubscriptionEventsContext = createContext<SubscriptionEventsContextType | undefined>(undefined);

export const SubscriptionEventsProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [subscriptionVersion, setSubscriptionVersion] = useState(0);
  const [subscribers, setSubscribers] = useState<Set<() => void>>(new Set());

  const notifySubscriptionChanged = useCallback(() => {
    setSubscriptionVersion(prev => prev + 1);
    
    // Notify all subscribers
    subscribers.forEach(callback => {
      try {
        callback();
      } catch (error) {
        console.warn('Error notifying subscription change subscriber:', error);
      }
    });
  }, [subscribers]);

  const subscribeToChanges = useCallback((callback: () => void) => {
    setSubscribers(prev => {
      const newSubscribers = new Set(prev);
      newSubscribers.add(callback);
      return newSubscribers;
    });

    // Return unsubscribe function
    return () => {
      setSubscribers(prev => {
        const newSubscribers = new Set(prev);
        newSubscribers.delete(callback);
        return newSubscribers;
      });
    };
  }, []);

  const value = {
    subscriptionVersion,
    notifySubscriptionChanged,
    subscribeToChanges
  };

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

export const useSubscriptionEvents = () => {
  const context = useContext(SubscriptionEventsContext);
  if (context === undefined) {
    throw new Error('useSubscriptionEvents must be used within a SubscriptionEventsProvider');
  }
  return context;
};
