import React, { useEffect, useState } from 'react';
import {
  LiveKitRoom,
  VideoConference,
  RoomAudioRenderer,
} from '@livekit/components-react';
import { useConvex } from 'convex/react';
import { api } from '../../../../convex/_generated/api';
import '@livekit/components-styles';
import { Track } from 'livekit-client';

const VoiceRoom = ({ channelId, channelName, userId, onDisconnect }) => {
    const [token, setToken] = useState('');
    const convex = useConvex();

    useEffect(() => {
        const fetchToken = async () => {
            try {
                const { token: lkToken } = await convex.action(api.voice.getToken, {
                    channelId,
                    userId,
                    username: localStorage.getItem('username') || 'Unknown'
                });
                if (lkToken) {
                    setToken(lkToken);
                } else {
                    console.error('Failed to get token');
                    onDisconnect();
                }
            } catch (err) {
                console.error(err);
                onDisconnect();
            }
        };

        if (channelId && userId) {
            fetchToken();
        }
    }, [channelId, userId]);

    if (!token) return <div style={{ color: 'white', padding: 20 }}>Connecting to Voice...</div>;

    const liveKitUrl = import.meta.env.VITE_LIVEKIT_URL;

    return (
        <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: '#000' }}>
            <div style={{
                padding: '10px 20px',
                background: '#1a1b1e',
                color: 'white',
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                borderBottom: '1px solid #2f3136'
            }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span>🔊</span>
                    <span style={{ fontWeight: 'bold' }}>{channelName}</span>
                    <span style={{ fontSize: 12, color: '#43b581', marginLeft: 8 }}>Connected</span>
                </div>
                <button
                    onClick={onDisconnect}
                    style={{
                        background: '#ed4245',
                        border: 'none',
                        color: 'white',
                        padding: '6px 12px',
                        borderRadius: 4,
                        cursor: 'pointer',
                        fontWeight: 'bold'
                    }}
                >
                    Disconnect
                </button>
            </div>

            <div style={{ flex: 1, position: 'relative' }}>
                <LiveKitRoom
                    video={false}
                    audio={true}
                    token={token}
                    serverUrl={liveKitUrl}
                    data-lk-theme="default"
                    style={{ height: '100%' }}
                    onDisconnected={onDisconnect}
                >
                    <VideoConference />
                    <RoomAudioRenderer />
                </LiveKitRoom>
            </div>
        </div>
    );
};

export default VoiceRoom;
