import React from 'react'
import classNames from 'classnames'
import { useZocksStore } from '../../../app'
import { selectActiveSpeakers, selectLocalParticipant, selectRemoteParticipants } from '../../../store'
import { getClassName, getMergedClassNames } from '../../common'
import { OnlineParticipantsListProps, ParticipantsListElementProps } from '../model'
import { ParticipantsList } from '../ParticipantsList'
import zocksStyle from '../ParticipantsList.module.scss'

export const OnlineParticipantsList: React.FC<OnlineParticipantsListProps> = ({ dismiss, components, styles }) => {
  const localParticipant = useZocksStore(selectLocalParticipant)
  const remoteParticipants = useZocksStore(selectRemoteParticipants)
  const allParticipants = [localParticipant, ...remoteParticipants]

  const ParticipantListElement = components?.ParticipantListElement ?? OnlineParticipantsListElement

  return (
    <ParticipantsList
      participants={allParticipants}
      dismiss={dismiss}
      components={{ ParticipantListElement }}
      styles={styles}
    />
  )
}

const OnlineParticipantsListElement: React.FC<ParticipantsListElementProps> = ({ participant, styles }) => {
  const activeSpeakers = useZocksStore(selectActiveSpeakers)
  const isSpeaking = activeSpeakers.some((participantId) => participantId === participant.id)
  const noAudio = participant.tracks.audioTracks.every((t) => t.isMuted)
  const noVideo = participant.tracks.videoTracks.every((t) => t.isMuted)
  const mergedStyles = getMergedClassNames(zocksStyle, styles)
  return (
    <div className={getClassName('participants-list__participant-container', mergedStyles)}>
      <div className={getClassName('participants-list__participant-avatar', mergedStyles)}>
        {participant.name?.slice(0, 1) || ''}
      </div>
      <div className={getClassName('participants-list__participant-name', mergedStyles)}>{participant.name}</div>
      <div className={getClassName('participants-list__participant-icons', mergedStyles)}>
        <div
          className={classNames({
            [getClassName('participants-list__participant-video-icon', mergedStyles)]: !noVideo,
            [getClassName('participants-list__participant-no-video-icon', mergedStyles)]: noVideo,
          })}
        />
        <div
          className={classNames({
            [getClassName('participants-list__participant-audio-icon', mergedStyles)]: !noAudio,
            [getClassName('participants-list__participant-no-audio-icon', mergedStyles)]: noAudio,
            [getClassName('participants-list__participant-speaking', mergedStyles)]: isSpeaking,
          })}
        />
      </div>
    </div>
  )
}
