import { useEffect, useState } from 'react';
import Pusher from 'pusher-js';
import { useSettings } from './use-settings';

interface Transcription {
  id: number;
  originalText: string;
  translatedText: string;
  clipStartTime: string;
  clipEndTime: string;
  sourceLanguage: string;
}

export function useSessionTranscriptions(sessionId: number) {
  const [transcriptions, setTranscriptions] = useState<Transcription[]>([]);
  const { settings } = useSettings();

  useEffect(() => {
    // Initialize Pusher
    const pusher = new Pusher(settings?.pusherKey || '', {
      cluster: settings?.pusherCluster || 'ap1',
    });

    // Subscribe to the session-specific channel
    const channelName = `session-${sessionId}-transcriptions`;
    const channel = pusher.subscribe(channelName);

    // Handle new transcriptions
    channel.bind('new-transcription', (data: { transcription: Transcription }) => {
      setTranscriptions(prev => [...prev, data.transcription]);
    });

    // Fetch existing transcriptions
    fetch(`/api/sessions/${sessionId}/transcriptions`)
      .then(res => res.json())
      .then(data => setTranscriptions(data.transcriptions))
      .catch(console.error);

    // Cleanup
    return () => {
      channel.unbind_all();
      channel.unsubscribe();
      pusher.disconnect();
    };
  }, [sessionId, settings]);

  return { transcriptions };
}
