import { useCallback, useEffect, useRef } from 'react';

import { type StreamVideoParticipant } from '@stream-io/video-react-sdk';

import { SPEAKING_THRESHOLD_MS } from '../constants';

const useSpeakingTracker = (participants: StreamVideoParticipant[]) => {
  const speakingStartedAtRef = useRef<Map<string, number | null>>(new Map());

  useEffect(() => {
    const map = speakingStartedAtRef.current;
    const activeSessionIds = new Set<string>();

    for (const participant of participants) {
      const { sessionId, isSpeaking } = participant;
      activeSessionIds.add(sessionId);

      const currentTimestamp = map.get(sessionId);

      if (
        isSpeaking &&
        (currentTimestamp === undefined || currentTimestamp === null)
      ) {
        map.set(sessionId, Date.now());
      } else if (
        !isSpeaking &&
        currentTimestamp !== undefined &&
        currentTimestamp !== null
      ) {
        map.set(sessionId, null);
      }
    }

    for (const sessionId of map.keys()) {
      if (!activeSessionIds.has(sessionId)) {
        map.delete(sessionId);
      }
    }
  }, [participants]);

  const isSpeakingOverThreshold = useCallback((sessionId: string): boolean => {
    const startedAt = speakingStartedAtRef.current.get(sessionId);
    if (startedAt === undefined || startedAt === null) return false;
    return Date.now() - startedAt >= SPEAKING_THRESHOLD_MS;
  }, []);

  return isSpeakingOverThreshold;
};

export default useSpeakingTracker;
