import React from 'react'
import { useZocksStore } from '../../../app'
import { selectLocalParticipant, selectScreenSharingParticipant } from '../../../store'
import { Participant } from '../../Participant'
import { ScreenShare } from '../../ScreenShare'
import { usePagedParticipants, useSortRemoteParticipantsBySpeakers } from '../hooks'
import { ScreenShareViewProps } from '../model'
import zocksStyle from './ParticipantsScreenShareView.module.scss'
import { getClassName, getMergedClassNames } from '../../common'

export const ParticipantsScreenShareView: React.FC<ScreenShareViewProps> = ({ pageSize = 4, components, styles }) => {
  const localParticipant = useZocksStore(selectLocalParticipant)
  const screenSharingParticipant = useZocksStore(selectScreenSharingParticipant)

  const { remoteParticipantsSortedBySpeakers } = useSortRemoteParticipantsBySpeakers()

  const allParticipants = [localParticipant, ...remoteParticipantsSortedBySpeakers]
  const { displayedParticipants, hasNextPage, hasPreviousPage, nextPage, previousPage } = usePagedParticipants(
    allParticipants,
    pageSize
  )

  const ParticipantElement = components?.Participant ?? Participant
  const ScreenShareElement = components?.ScreenShare ?? ScreenShare

  const mergedStyles = getMergedClassNames(zocksStyle, styles)

  return (
    <div className={getClassName('participants-screen-share-view', mergedStyles)}>
      <div className={getClassName('participants-screen-share-view__current-share', mergedStyles)}>
        {screenSharingParticipant && (
          <ScreenShareElement participant={screenSharingParticipant} styles={mergedStyles} />
        )}
      </div>
      {hasPreviousPage && <PreviousButton onClick={previousPage} />}
      <div className={getClassName('participants-screen-share-view__participants-container', mergedStyles)}>
        <div className={getClassName('participants-screen-share-view__participants', mergedStyles)}>
          {displayedParticipants.map((participant) => (
            <ParticipantElement key={participant.id} participant={participant} styles={mergedStyles} />
          ))}
        </div>
      </div>
      {hasNextPage && <NextButton onClick={nextPage} />}
    </div>
  )
}

const PreviousButton: React.FC<{ onClick: () => void }> = ({ onClick }) => (
  <button
    className='participants-screen-share-view__button participants-screen-share-view__previous-button'
    onClick={onClick}
    aria-label='Previous'
  >
    <div className='participants-screen-share-view__previous-button-icon' />
  </button>
)

const NextButton: React.FC<{ onClick: () => void }> = ({ onClick }) => (
  <button
    className='participants-screen-share-view__button participants-screen-share-view__next-button'
    onClick={onClick}
    aria-label='Next'
  >
    <div className='participants-screen-share-view__next-button-icon' />
  </button>
)
