import { useCallback, useState } from 'react';
import { useNavigation } from '@react-navigation/native';
import { toast } from 'sonner-native';
import { apiClient } from '@/api/client';
import { toUserMessage } from '@/lib/errors';
import type { RootStackParamList } from '@/navigation/types';
import type { NativeStackNavigationProp } from '@react-navigation/native-stack';

/**
 * Mirrors desktop's `handleOpenHuddle` (stream-view.tsx) — fetch a fresh
 * LiveKit token from Orion for the {network, stream} pair and hand off to
 * the dedicated huddle screen. Joining and starting are the same operation
 * server-side: minting a token implicitly creates/joins the room.
 */
export function useOpenHuddle() {
  const navigation =
    useNavigation<NativeStackNavigationProp<RootStackParamList>>();
  const [loading, setLoading] = useState(false);

  const open = useCallback(
    async (networkId: string, streamId: string, streamName: string) => {
      if (loading) return;
      setLoading(true);
      try {
        const { token, server_url } = await apiClient.getLivekitToken(
          networkId,
          streamId,
        );
        navigation.navigate('Huddle', {
          networkId,
          streamId,
          streamName,
          token,
          serverUrl: server_url,
        });
      } catch (err) {
        toast.error(toUserMessage(err));
      } finally {
        setLoading(false);
      }
    },
    [navigation, loading],
  );

  return { open, loading };
}
