import React from 'react'
import { Track } from '@zocks-communications/client-sdk-js'
import { useLeaveOnUnload, useParticipant, useZocksActions, useZocksSession } from '../../store'
import {
  Audio,
  JoinPage,
  ParticipantProps,
  Participants,
  RoomControls,
  ScreenShareProps,
  Video,
  ViewSwitcher,
} from '../../components'
import classNames from 'classnames'
import './ManualSubscription.scss'

export const ManualSubscription: React.FC = () => {
  const zocksActions = useZocksActions({
    accountId: '',
  })
  const { sessionActions } = zocksActions
  const { localParticipantIsConnected } = useZocksSession()
  useLeaveOnUnload(sessionActions.leave)

  return (
    <div className='manual-subscription'>
      {!localParticipantIsConnected ? (
        <>
          <JoinPage
            createRoomAction={sessionActions.createRoom}
            joinAction={sessionActions.join}
            joinOptions={{ autoSubscribe: false }}
          />
        </>
      ) : (
        <>
          <div className='room-controls'>
            <RoomControls zocksActions={zocksActions} />
          </div>
          <ViewSwitcher />
          <Participants
            speakerPageSize={4}
            components={{
              Participant: ManualSubscriptableParticipant,
              ScreenShare: ManualSubscriptableScreenShare,
            }}
          />
        </>
      )}
    </div>
  )
}

const ManualSubscriptableParticipant: React.FC<ParticipantProps> = ({ participant, withAudio = false }) => {
  const {
    name,
    isLocal,
    isSpeaking,
    tracks: { primaryVideoTrack, primaryAudioTrack },
  } = useParticipant(participant)

  const hasVideoTrack = !!primaryVideoTrack
  const videoTrackIsSubscribed = hasVideoTrack && primaryVideoTrack.isSubscribed
  const videoTrackIsNotMuted = videoTrackIsSubscribed && !primaryVideoTrack.isMuted

  const hasAudioTrack = !!primaryAudioTrack
  const audioTrackIsSubscribed = hasAudioTrack && primaryAudioTrack.isSubscribed
  const audioTrackIsNotMuted = audioTrackIsSubscribed && !primaryAudioTrack.isMuted

  return (
    <div className='participant'>
      <div className='participant__name'>{name}</div>
      <div
        className={classNames('participant__video-container', {
          'participant__video-container--speaking': isSpeaking,
          'participant__video-container--local': isLocal,
        })}
      >
        {videoTrackIsNotMuted ? (
          <Video videoStream={primaryVideoTrack.track} />
        ) : (
          <div className='participant__avatar'>{name?.slice(0, 1)}</div>
        )}
      </div>
      {!isLocal && (
        <div className='participant__subscribe-buttons'>
          {hasVideoTrack && (
            <button onClick={() => changeTrackSubscription(primaryVideoTrack.track)}>
              {videoTrackIsSubscribed ? 'Unsubscribe video' : 'Subscribe video'}
            </button>
          )}
          {hasAudioTrack && (
            <button onClick={() => changeTrackSubscription(primaryAudioTrack.track)}>
              {audioTrackIsSubscribed ? 'Unsubscribe audio' : 'Subscribe audio'}
            </button>
          )}
        </div>
      )}

      {withAudio && audioTrackIsNotMuted && !isLocal && <Audio audioStream={primaryAudioTrack.track} />}
    </div>
  )
}

const ManualSubscriptableScreenShare: React.FC<ScreenShareProps> = ({ participant }) => {
  const {
    name,
    isLocal,
    tracks: { screenShareTrack },
  } = useParticipant(participant)

  const hasScreenShareTrack = !!screenShareTrack
  const screenShareTrackIsSubscribed = hasScreenShareTrack && screenShareTrack.isSubscribed

  return (
    <div className='screen-share'>
      {screenShareTrackIsSubscribed ? (
        <Video videoStream={screenShareTrack.track} />
      ) : (
        <div className='participant__avatar'>{name?.slice(0, 1)}</div>
      )}
      {!isLocal && (
        <div className='participant__subscribe-buttons'>
          {hasScreenShareTrack && (
            <button onClick={() => changeTrackSubscription(screenShareTrack.track)}>
              {screenShareTrackIsSubscribed ? 'Unsubscribe screen share' : 'Subscribe screen share'}
            </button>
          )}
        </div>
      )}
    </div>
  )
}

const changeTrackSubscription = (track: Track) => {
  if (track.isSubscribed) {
    track.unsubscribe()
  } else {
    track.subscribe()
  }
}
