import React, { FC, useEffect, useRef } from 'react';
import { useRealtimeKitSelector } from '../../src';

const PeerView: FC<{
  peerId: string;
}> = ({ peerId }) => {
    const {
        audioEnabled, audioTrack, videoEnabled, videoTrack,
    } = useRealtimeKitSelector((meeting) => meeting.participants.active.get(peerId))!;
    const videoRef = useRef<HTMLVideoElement>(null);
    const audioRef = useRef<HTMLAudioElement>(null);

    useEffect(() => {
        if (!audioRef.current) return;

        if (audioEnabled && audioTrack) {
            const stream = new MediaStream();
            stream.addTrack(audioTrack);
            audioRef.current.srcObject = stream;
        } else {
            audioRef.current.srcObject = null;
        }
    }, [audioEnabled, audioTrack]);

    useEffect(() => {
        if (!videoRef.current) return;

        if (videoEnabled && videoTrack) {
            const stream = new MediaStream();
            stream.addTrack(videoTrack);
            videoRef.current.srcObject = stream;
        } else {
            videoRef.current.srcObject = null;
        }
    }, [videoEnabled, videoTrack]);

    return (
        <div>
            <video
                width={100}
                height={100}
                ref={videoRef}
                autoPlay
                playsInline
                style={{
                    display: videoEnabled ? 'block' : 'none',
                    background: 'wheat',
                }}
            />
            <audio ref={audioRef} autoPlay />
        </div>
    );
};

function ActiveParticipants() {
    const activeParticipants = useRealtimeKitSelector(
        (meeting) => meeting.participants.active,
    );

    return (
        <div>
            {activeParticipants?.toArray().map((peer: { id: string }) => (
                <PeerView key={peer.id} peerId={peer.id} />
            ))}
        </div>
    );
}

function Participants() {
    const roomJoined = useRealtimeKitSelector(
        (meeting) => meeting.self.roomJoined,
    );
    const joinedParticipants = useRealtimeKitSelector(
        (meeting) => meeting.participants.joined,
    );

    if (!joinedParticipants || !roomJoined) {
        return null;
    }

    return (
        <fieldset className="section">
            <legend>Participants</legend>
            <div>
                <h2>Active Participants</h2>
                <ActiveParticipants />
            </div>
            <div>
                <h2>Joined Participants</h2>
                <ul style={{ paddingLeft: '1.25rem' }}>
                    {joinedParticipants
                        ?.toArray()
                        .map(
                            (peer: {
                id: string;
                audioEnabled: boolean;
                name: string;
                videoEnabled: boolean;
              }) => (
                                <li key={peer.id}>
                                    {peer.name}
                                    {' '}
- audio:
                                    {' '}
                                    <span className="token">
                                        {JSON.stringify(peer.audioEnabled)}
                                    </span>
                  , video:
                                    {' '}
                                    <span className="token">
                                        {JSON.stringify(peer.videoEnabled)}
                                    </span>
                                </li>
                            ),
                        )}
                </ul>
            </div>
        </fieldset>
    );
}

export default Participants;
