import {useEffect, useState} from 'react';
import {chatMembershipsHandler} from '@config/synchroniser/handlers/ChatMembershipsHandler';

type SyncState = 'fetching' | 'processed' | 'pending' | 'failed' | 'cancelled';

/**
 * Hook to subscribe to membership sync state changes for a specific channel
 * @param channelId - The channel ID to monitor
 * @returns Current sync state for the channel
 */
export function useMembershipSyncState(channelId: string): SyncState {
  const [state, setState] = useState<SyncState>(() =>
    chatMembershipsHandler.getChannelState(channelId),
  );

  useEffect(() => {
    // Subscribe to changes for this specific channel
    const unsubscribe = chatMembershipsHandler.subscribeToChannel(
      channelId,
      (channel, newState) => {
        setState(newState);
      },
    );

    // Clean up subscription on unmount or channel change
    return unsubscribe;
  }, [channelId]);

  return state;
}
