import { useMemo } from 'react';
import { useSelector } from 'react-redux';
import { selectActiveSession, selectInSession } from '../store/features/activeSessionSlice';

const useSessionHelper = () => {
  // Phase 4: Replace CurrentSessionContext with Redux
  const currentSession = useSelector(selectActiveSession);
  const inSession = useSelector(selectInSession);

  const sessionHelper = useMemo(() => {
    const inSessionCheck = () => {
      return inSession;
    };

    const participants = () => {
      if (currentSession) {
        return currentSession.participants || [];
      }
      return [];
    };

    const users = () => {
      const found = {};
      participants().forEach(participant => {
        found[participant.user.id] = participant.user;
      });
      return found;
    };

    const findParticipantByUserId = userId => {
      let foundParticipant = null;
      participants().forEach(participant => {
        if (participant.user.id === userId) {
          foundParticipant = participant;
        }
      });
      return foundParticipant;
    };

    const otherParticipants = () => {
      const others = [];
      const clientId = window.JK?.currentUserId;
      participants().forEach(participant => {
        const myTrack = clientId === participant.client_id;
        if (!myTrack) {
          others.push(participant);
        }
      });
      return others;
    };

    const sessionController = () => {
      const info = {
        can_control: false,
        session_controller: null
      };

      if (currentSession) {
        if (currentSession.session_controller_id === null) {
          info.can_control = true;
          info.session_controller = null;
        } else {
          participants().forEach(participant => {
            if (participant.user.id === currentSession.session_controller_id) {
              info.session_controller = participant;
              info.can_control = participant.user.id === window.JK?.currentUserId;
            }
          });
        }
      }

      return info;
    };

    const isMetronomeOpen = () => {
      return currentSession?.metronome_active || false;
    };

    const isPlayingRecording = () => {
      return !!(currentSession && currentSession.claimed_recording);
    };

    const recordedTracks = () => {
      if (currentSession && currentSession.claimed_recording) {
        return currentSession.claimed_recording.recording.recorded_tracks;
      }
      return null;
    };

    const recordedBackingTracks = () => {
      if (currentSession && currentSession.claimed_recording) {
        return currentSession.claimed_recording.recording.recorded_backing_tracks;
      }
      return null;
    };

    const backingTracks = () => {
      let backingTracks = [];
      participants().forEach(participant => {
        if (participant.backing_tracks && participant.backing_tracks.length > 0) {
          backingTracks = participant.backing_tracks;
        }
      });
      return backingTracks;
    };

    const backingTrack = () => {
      if (currentSession) {
        return {
          path: currentSession.backing_track_path
        };
      }
      return null;
    };

    const jamTracks = () => {
      if (currentSession && currentSession.jam_track) {
        return currentSession.jam_track.tracks.filter(
          track => track.track_type === 'Track' || track.track_type === 'Click'
        );
      }
      return null;
    };

    const jamTrackMixdown = () => {
      return { id: currentSession?.jam_track?.mixdown?.id };
    };

    const jamTrackName = () => {
      return currentSession?.jam_track?.name || null;
    };

    const recordedJamTracks = () => {
      if (currentSession && currentSession.claimed_recording) {
        return currentSession.claimed_recording.recording.recorded_jam_track_tracks;
      }
      return null;
    };

    const recordedJamTrackName = () => {
      const jam_track = currentSession?.claimed_recording?.recording?.jam_track;
      return jam_track ? jam_track.name : null;
    };

    const recordingName = () => {
      return currentSession?.claimed_recording?.name || null;
    };

    const getParticipant = clientId => {
      let found = null;
      participants().forEach(participant => {
        if (participant.client_id === clientId) {
          found = participant;
        }
      });

      if (!found) {
        console.warn('unable to find participant with clientId: ' + clientId);
      }

      return found;
    };

    const id = () => {
      return currentSession?.id || null;
    };

    const musicianAccess = () => {
      if (!currentSession.musician_access && !currentSession.approval_required) {
        return 'only-rsvp';
      }else if(currentSession.musician_access && currentSession.approval_required){
        return 'musicians-approval';
      }else if(currentSession.musician_access && !currentSession.approval_required){
        return 'musicians';
      }
    };

    return {
      inSession: inSessionCheck,
      participants,
      users,
      findParticipantByUserId,
      otherParticipants,
      sessionController,
      isMetronomeOpen,
      isPlayingRecording,
      recordedTracks,
      recordedBackingTracks,
      backingTracks,
      backingTrack,
      jamTracks,
      jamTrackMixdown,
      jamTrackName,
      recordedJamTracks,
      recordedJamTrackName,
      recordingName,
      getParticipant,
      id,
    };
  }, [currentSession, inSession]);

  return sessionHelper;
};

export default useSessionHelper;
