'use client';
import { useRef, useEffect, useState } from 'react';
import { TokenSource, ConnectionState, Track, TrackPublication } from 'livekit-client';
import {
  SessionProvider,
  useSession,
  ControlBar,
  RoomAudioRenderer,
  useRoomContext,
} from '@livekit/components-react';
import '@livekit/components-styles';

function RoomContent() {
  const room = useRoomContext();
  const [isConnected, setIsConnected] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [connectionState, setConnectionState] = useState<ConnectionState>(room.state);
  const [micEnabled, setMicEnabled] = useState(false);
  const [micMuted, setMicMuted] = useState(true);
  const [remoteParticipants, setRemoteParticipants] = useState<string[]>([]);

  useEffect(() => {
    const handleConnected = () => {
      console.log('✅ Connected to room:', room.name);
      setIsConnected(true);
      setError(null);
      setConnectionState(room.state);
      
      // Check microphone state
      const micTrack = room.localParticipant.getTrackPublication(Track.Source.Microphone);
      if (micTrack) {
        setMicEnabled(true);
        setMicMuted(micTrack.isMuted);
        console.log('🎤 Microphone track:', {
          enabled: true,
          muted: micTrack.isMuted,
          subscribed: micTrack.isSubscribed,
        });
      }
    };

    const handleDisconnected = () => {
      console.log('❌ Disconnected from room');
      setIsConnected(false);
      setConnectionState(room.state);
      setMicEnabled(false);
      setRemoteParticipants([]);
    };

    const handleConnectionStateChanged = (state: ConnectionState) => {
      console.log('Connection state changed:', state);
      setConnectionState(state);
      if (state === ConnectionState.Connected) {
        handleConnected();
      } else if (state === ConnectionState.Disconnected) {
        handleDisconnected();
      }
    };

    const handleTrackPublished = (publication: TrackPublication, participant: any) => {
      console.log('📡 Track published:', {
        source: publication.source,
        kind: publication.kind,
        participant: participant.identity,
        isLocal: participant === room.localParticipant,
      });
      
      if (publication.source === Track.Source.Microphone && participant === room.localParticipant) {
        setMicEnabled(true);
        setMicMuted(publication.isMuted);
      }
    };

    const handleTrackSubscribed = (track: any, publication: TrackPublication, participant: any) => {
      console.log('🎧 Track subscribed:', {
        source: publication.source,
        kind: publication.kind,
        participant: participant.identity,
        isLocal: participant === room.localParticipant,
      });
      
      // If it's a remote audio track, attach it
      if (track.kind === Track.Kind.Audio && participant !== room.localParticipant) {
        track.attach();
        console.log('🔊 Remote audio track attached');
      }
    };

    const handleParticipantConnected = (participant: any) => {
      console.log('👤 Participant connected:', participant.identity);
      setRemoteParticipants(prev => [...prev, participant.identity]);
    };

    const handleParticipantDisconnected = (participant: any) => {
      console.log('👤 Participant disconnected:', participant.identity);
      setRemoteParticipants(prev => prev.filter(id => id !== participant.identity));
    };

    // Set initial state
    setConnectionState(room.state);
    if (room.state === ConnectionState.Connected) {
      setIsConnected(true);
      const micTrack = room.localParticipant.getTrackPublication(Track.Source.Microphone);
      if (micTrack) {
        setMicEnabled(true);
        setMicMuted(micTrack.isMuted);
      }
    }

    // Set up event listeners
    room.on('connected', handleConnected);
    room.on('disconnected', handleDisconnected);
    room.on('connectionStateChanged', handleConnectionStateChanged);
    room.on('trackPublished', handleTrackPublished);
    room.on('trackSubscribed', handleTrackSubscribed);
    room.on('participantConnected', handleParticipantConnected);
    room.on('participantDisconnected', handleParticipantDisconnected);

    // Enable microphone track when connected
    const enableMicrophone = async () => {
      if (room.state === ConnectionState.Connected) {
        try {
          console.log('🎤 Attempting to enable microphone...');
          await room.localParticipant.setMicrophoneEnabled(true);
          
          // Wait a bit and check the track
          setTimeout(() => {
            const micTrack = room.localParticipant.getTrackPublication(Track.Source.Microphone);
            if (micTrack) {
              setMicEnabled(true);
              setMicMuted(micTrack.isMuted);
              console.log('✅ Microphone enabled:', {
                enabled: true,
                muted: micTrack.isMuted,
                trackSid: micTrack.trackSid,
              });
            } else {
              console.warn('⚠️ Microphone track not found after enabling');
            }
          }, 500);
        } catch (err) {
          console.error('❌ Failed to enable microphone:', err);
          setError(err instanceof Error ? err.message : 'Failed to enable microphone');
        }
      }
    };

    if (room.state === ConnectionState.Connected) {
      enableMicrophone();
    } else {
      room.once('connected', enableMicrophone);
    }

    // Check for existing remote participants
    room.remoteParticipants.forEach((participant) => {
      setRemoteParticipants(prev => [...prev, participant.identity]);
      console.log('👤 Existing remote participant:', participant.identity);
      
      // Check for audio tracks
      participant.audioTrackPublications.forEach((publication) => {
        if (publication.track) {
          console.log('🔊 Found remote audio track:', publication.trackSid);
        }
      });
    });

    return () => {
      room.off('connected', handleConnected);
      room.off('disconnected', handleDisconnected);
      room.off('connectionStateChanged', handleConnectionStateChanged);
      room.off('trackPublished', handleTrackPublished);
      room.off('trackSubscribed', handleTrackSubscribed);
      room.off('participantConnected', handleParticipantConnected);
      room.off('participantDisconnected', handleParticipantDisconnected);
    };
  }, [room]);

  return (
    <div style={{ padding: 20 }}>
      <h2>AI Interview — Candidate</h2>
      {error && (
        <div style={{ color: 'red', marginBottom: 10, padding: 10, background: '#fee' }}>
          <strong>Error:</strong> {error}
        </div>
      )}
      <div style={{ marginBottom: 10, padding: 10, background: '#f0f0f0' }}>
        <div><strong>Connection State:</strong> {connectionState}</div>
        {isConnected && (
          <div style={{ color: 'green', marginTop: 5 }}>
            ✅ Connected to room: {room.name}
          </div>
        )}
        <div style={{ marginTop: 5 }}>
          <strong>Microphone:</strong>{' '}
          {micEnabled ? (
            <span style={{ color: micMuted ? 'red' : 'green' }}>
              {micMuted ? '🔴 Muted' : '🟢 Active'}
            </span>
          ) : (
            <span style={{ color: 'orange' }}>⚠️ Not enabled</span>
          )}
        </div>
        <div style={{ marginTop: 5 }}>
          <strong>Remote Participants:</strong>{' '}
          {remoteParticipants.length > 0 ? (
            <span style={{ color: 'green' }}>
              {remoteParticipants.join(', ')}
            </span>
          ) : (
            <span style={{ color: 'orange' }}>None (Agent not connected?)</span>
          )}
        </div>
      </div>
      <ControlBar 
        controls={{ 
          microphone: true, 
          camera: false, 
          screenShare: false 
        }} 
      />
      <RoomAudioRenderer />
    </div>
  );
}

function Inner() {
  const [startError, setStartError] = useState<string | null>(null);
  const [isStarting, setIsStarting] = useState(false);

  const tokenSource = useRef(
    TokenSource.custom(async () => {
      try {
        console.log('🔑 Fetching token...');
        const response = await fetch('http://localhost:3000/api/token?name=Candidate&room=interview-room');
        if (!response.ok) {
          const errorText = await response.text();
          throw new Error(`Failed to fetch token: ${response.status} ${response.statusText} - ${errorText}`);
        }
        const data = await response.json();
        console.log('✅ Token data received:', { 
          hasToken: !!data.token,
          hasUrl: !!data.url,
          url: data.url
        });
        
        if (!data.token) {
          throw new Error('Token is missing from response');
        }
        if (!data.url) {
          throw new Error('URL is missing from response');
        }

        return {
          participantToken: data.token,
          serverUrl: data.url,
        };
      } catch (err) {
        console.error('❌ Token fetch error:', err);
        setStartError(err instanceof Error ? err.message : 'Failed to fetch token');
        throw err;
      }
    })
  ).current;

  const session = useSession(tokenSource);

  useEffect(() => {
    // Start the session
    const startSession = async () => {
      // Don't start if already connected or connecting
      if (session.connectionState === ConnectionState.Connected || 
          session.connectionState === ConnectionState.Connecting) {
        console.log('Session already connected/connecting, skipping start');
        return;
      }

      try {
        setIsStarting(true);
        setStartError(null);
        console.log('🚀 Starting session...', {
          currentState: session.connectionState,
          isConnected: session.isConnected
        });
        
        await session.start({
          tracks: {
            microphone: {
              enabled: true,
              publishOptions: {
                source: Track.Source.Microphone,
              },
            },
          },
        });
        
        console.log('✅ Session started successfully', {
          connectionState: session.connectionState,
          isConnected: session.isConnected,
        });
      } catch (err) {
        console.error('❌ Failed to start session:', err);
        setStartError(err instanceof Error ? err.message : 'Failed to start session');
      } finally {
        setIsStarting(false);
      }
    };

    // Small delay to ensure session is ready
    const timer = setTimeout(() => {
      startSession();
    }, 100);

    return () => {
      clearTimeout(timer);
    };
  }, [session]);

  return (
    <SessionProvider session={session}>
      {startError && (
        <div style={{ padding: 20, color: 'red', background: '#fee' }}>
          <h3>Start Error</h3>
          <p>{startError}</p>
          <button onClick={() => window.location.reload()}>Retry</button>
        </div>
      )}
      {isStarting && (
        <div style={{ padding: 20 }}>
          <p>Starting session...</p>
        </div>
      )}
      <RoomContent />
    </SessionProvider>
  );
}

export default function App() {
  return <Inner />;
}
