import { useState } from 'react'
import { sortParticipantsBySpeakers } from './utils'
import { useZocksStore } from '../../app'
import { ParticipantModel, selectRemoteParticipants, selectLastSpeakers } from '../../store'

export const usePagedParticipants = (participants: ParticipantModel[], pageSize: number) => {
  const [page, setPage] = useState(0)
  const start = page * pageSize
  const end = start + pageSize
  const displayedParticipants = participants.slice(start, end)

  const nextPage = () => {
    setPage((page) => page + 1)
  }

  const previousPage = () => {
    setPage((page) => page - 1)
  }

  const hasNextPage = end < participants.length
  const hasPreviousPage = start > 0

  return {
    displayedParticipants,
    hasNextPage,
    hasPreviousPage,
    nextPage,
    previousPage,
  }
}

export const useSortRemoteParticipantsBySpeakers = () => {
  const lastSpeakers = useZocksStore(selectLastSpeakers)
  const remoteParticipants = useZocksStore(selectRemoteParticipants)

  const remoteParticipantsSortedBySpeakers = sortParticipantsBySpeakers(lastSpeakers, remoteParticipants)

  return {
    remoteParticipantsSortedBySpeakers,
  }
}

export const useSortRemoteParticipantsForGridView = (pageSize: number) => {
  const lastSpeakers = useZocksStore(selectLastSpeakers)
  const remoteParticipants = useZocksStore(selectRemoteParticipants)

  if (remoteParticipants.length < pageSize) {
    return remoteParticipants
  }

  const lastSpeakingParticipantsNotOnFirstPage = remoteParticipants
    .slice(pageSize - 1)
    .filter((p) => p.id && lastSpeakers.includes(p.id))

  const participantsToMove: ParticipantModel[] = []
  for (const lastSpeaker of lastSpeakers) {
    const participantIndex = remoteParticipants.findIndex((p) => p.id === lastSpeaker)
    if (participantIndex < 0) {
      continue
    }
    if (
      lastSpeakingParticipantsNotOnFirstPage.some((p) => p.id === lastSpeaker) ||
      participantIndex + lastSpeakingParticipantsNotOnFirstPage.length >= pageSize - 1
    ) {
      participantsToMove.push(remoteParticipants[participantIndex])
    }
  }

  const others = remoteParticipants.filter((p) => !participantsToMove.some((p2) => p2.id === p.id))

  return [...participantsToMove, ...others]
}
