import { useCurrentProfile } from '@/hooks/profile';
import { AudioSession, useVoiceAssistant, setLogLevel, LiveKitRoom } from '@livekit/react-native';
import { useConnectionState, useLocalParticipant, useRoomContext } from '@livekit/components-react';
import {
  ConnectionState,
  LocalAudioTrack,
  LocalParticipant,
  LogLevel,
  RoomOptions,
} from 'livekit-client';
import { useEffect, useMemo, useState } from 'react';
import { ActiveCallView } from './ActiveCallView';
import { Agent } from '@/hooks/agents';
import { observeParticipantMedia, ParticipantMedia } from '@livekit/components-core';
import { setIsAudioActiveAsync } from 'expo-audio';
import { KrispNoiseFilter } from '@livekit/react-native-krisp-noise-filter';
import { captureMessage } from '@sentry/react-native';
import { Alert, AppState } from 'react-native';
import { analytics } from '@/utils/analytics';

setLogLevel(LogLevel.warn);

export function LiveKitRoomWrapper({
  onEndPress,
  serverUrl,
  token,
  agent,
  onStateChange,
  options,
}: {
  onEndPress: () => void;
  serverUrl: string;
  token: string;
  agent: Agent;
  options?: RoomOptions & { enableKrisp?: boolean };
  onStateChange: (state: ConnectionState) => void;
}) {
  const [connected, setConnected] = useState(false);
  useEffect(() => {
    let retryCount = 0;
    const start = async () => {
      try {
        await AudioSession.setAppleAudioConfiguration({
          audioCategory: 'playAndRecord',
          audioMode: 'videoChat',
          audioCategoryOptions: ['allowAirPlay', 'allowBluetooth', 'defaultToSpeaker'],
        });
        await setIsAudioActiveAsync(true);
        await AudioSession.startAudioSession();
        setConnected(true);
      } catch (error) {
        analytics.track('Audio Session Error' as any, {
          error,
          retryCount,
          component: 'LiveKit',
        });
        captureMessage('Error setting up audio session', {
          level: 'warning',
          extra: {
            error,
            retryCount,
          },
        });
        Alert.alert('Error setting up audio session', 'Please try again later', [
          { text: 'Cancel', onPress: onEndPress },
          { text: 'OK', onPress: start },
        ]);
        retryCount++;
      }
    };

    start();

    return () => {
      const stopAudio = async () => {
        try {
          await AudioSession.setAppleAudioConfiguration({
            audioCategory: 'playback',
            audioMode: 'default',
            audioCategoryOptions: ['allowAirPlay', 'allowBluetooth', 'mixWithOthers'],
          });
          await setIsAudioActiveAsync(false);
          await AudioSession.stopAudioSession();
        } catch (error) {
          console.error(error);
        }
      };
      stopAudio();
    };
  }, [onEndPress]);

  useEffect(() => {
    // Fix for orientation change in the background
    const subscription = AppState.addEventListener('change', async state => {
      let change = 'failed';
      if (state === 'active') {
        try {
          await AudioSession.setAppleAudioConfiguration({
            audioCategory: 'playAndRecord',
            audioMode: 'videoChat',
            audioCategoryOptions: ['allowAirPlay', 'allowBluetooth', 'defaultToSpeaker'],
          });
          await setIsAudioActiveAsync(true);
          change = 'activated';
        } catch (error) {
          console.error('Error setting up audio session', error);
        }
        analytics.track('Audio Session AppState Changed' as any, {
          state,
          change,
          component: 'LiveKit',
        });
      }
    });

    return () => {
      subscription.remove();
    };
  }, []);
  return (
    <LiveKitRoom
      serverUrl={serverUrl}
      token={token}
      connect={connected}
      audio={true}
      video={false}
      options={options}
      onError={error => {
        console.error('LiveKitRoom error', error);
      }}
      onMediaDeviceFailure={failure => {
        console.error('LiveKitRoom media device failure', failure);
      }}
      onEncryptionError={error => {
        console.error('LiveKitRoom encryption error', error);
      }}>
      <RoomView
        onEndPress={onEndPress}
        agent={agent}
        onStateChange={onStateChange}
        enableKrisp={options?.enableKrisp !== false}
      />
    </LiveKitRoom>
  );
}