import React, { useMemo, memo } from 'react';
import { useSelector } from 'react-redux';
import { selectActiveSession } from '../../store/features/activeSessionSlice';
import { useAuth } from '../../context/UserAuth';
import JKSessionAudioInputs from './JKSessionAudioInputs';
import { getAvatarUrl, getInstrumentIcon45_inverted } from '../../helpers/utils';

const JKSessionRemoteTracks = memo(function JKSessionRemoteTracks({ mixerHelper, sessionModel }) {
  // Phase 4: Replace CurrentSessionContext with Redux
  const currentSession = useSelector(selectActiveSession);
  const { currentUser } = useAuth();

  const remoteParticipantsData = useMemo(() => {
    if (!currentSession || !currentUser) return [];

    // Get all participants (including current user)
    const allParticipants = sessionModel.participants();

    // Filter out current user to get remote participants
    const remoteParticipants = allParticipants.filter(participant =>
      participant.user.id !== currentUser.id
    );

    // Compute tracks for each remote participant
    return remoteParticipants.map(participant => {
      const tracks = [];
      const connStatsClientId = participant.client_role === 'child' && participant.parent_client_id
        ? participant.parent_client_id
        : participant.client_id;

      const photoUrl = getAvatarUrl(participant.user.photo_url);
      const name = participant.user.name;

      for (const track of participant.tracks || []) {
        const mixerData = mixerHelper.findMixerForTrack(participant.client_id, track, false, mixerHelper.mixMode);
        const hasMixer = !!mixerData.mixer;

        const instrumentIcon = getInstrumentIcon45_inverted(track.instrument_id || track.instrument);
        const trackName = name;

        tracks.push({
          track,
          mixerFinder: [participant.client_id, track, false],
          mixers: mixerData,
          hasMixer,
          name,
          trackName,
          instrumentIcon,
          photoUrl,
          clientId: participant.client_id,
          userId: participant.user.id,
          connStatsClientId
        });
      }

      return {
        participant,
        tracks,
        hasChat: false // Remote participants don't have chat in this context
      };
    });
  }, [currentSession, currentUser, sessionModel, mixerHelper]);

  return (
    <div className='d-flex' style={{ gap: '1rem' }}>
      {remoteParticipantsData.map(({ participant, tracks, hasChat }) => (
        <JKSessionAudioInputs
          key={participant.client_id}
          myTracks={tracks}
          chat={hasChat ? {} : null} // No chat for remote users in this implementation
          mixerHelper={mixerHelper}
          isRemote={true}
        />
      ))}
    </div>
  );
});

JKSessionRemoteTracks.displayName = 'JKSessionRemoteTracks';

export default JKSessionRemoteTracks;
