import React from 'react'
import { render, screen } from '@testing-library/react'

import { ConnectionQuality } from '@zocks-communications/client-sdk-js'
import { ParticipantsList } from './ParticipantsList'
import { ParticipantModel } from '../../../store'

const testParticipant: ParticipantModel = {
  id: 'Participant id: 1',
  name: 'Participant name: 1',
  tracks: {
    audioTracks: [],
    videoTracks: [],
    screenShareTrack: null,
  },
  connectionQuality: ConnectionQuality.EXCELLENT,
}

test('renders participant avatars and names by default', () => {
  const mockParticipants: ParticipantModel[] = [
    {
      ...testParticipant,
      id: 'Participant id: 1',
      name: 'Participant name: 1',
    },
    {
      ...testParticipant,
      id: 'Participant id: 2',
      name: 'Participant name: 2',
    },
  ]
  render(<ParticipantsList participants={mockParticipants} />)

  expect(screen.getByText('Participant name: 1')).toBeInTheDocument()
  expect(screen.getByText('Participant name: 2')).toBeInTheDocument()
  expect(screen.getAllByText('P')).toHaveLength(2)
})

test('does not render a dismiss button if the handler is not given', () => {
  render(<ParticipantsList participants={[]} />)

  expect(screen.queryByRole('button', { name: 'Dismiss' })).not.toBeInTheDocument()
})

test('calls the dismiss handler when a handler is given and the Dismiss button is clicked', () => {
  const mockDismiss = jest.fn()
  render(<ParticipantsList participants={[]} dismiss={mockDismiss} />)

  const dismissButton = screen.getByRole('button', { name: 'Dismiss' })
  dismissButton.click()

  expect(mockDismiss).toHaveBeenCalledTimes(1)
})

test('uses a custom participant element renderer when given', () => {
  const CustomParticipantElement = () => <div>custom participant component</div>
  const participants = [testParticipant]
  render(
    <ParticipantsList participants={participants} components={{ ParticipantListElement: CustomParticipantElement }} />
  )

  expect(screen.getByText('custom participant component')).toBeInTheDocument()
  expect(screen.queryByText('Participant name: 1')).not.toBeInTheDocument()
})

test('does not render avatar and name for participants without a name', () => {
  const participants = [{ ...testParticipant, name: '' }]
  render(<ParticipantsList participants={participants} />)

  expect(screen.queryByText(/./)).not.toBeInTheDocument()
})
