import { mock } from 'jest-mock-extended'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { RecipientSelector } from './RecipientSelector'
import { ParticipantModel, PUBLIC_CHAT_RECIPIENT } from '../../../store'

const testRemoteParticipants: ParticipantModel[] = [
  mock<ParticipantModel>({ id: 'testRemoteParticipantId1', name: 'Test Remote Participant 1' }),
  mock<ParticipantModel>({ id: 'testRemoteParticipantId2', name: 'Test Remote Participant 2' }),
]

test('renders a select with the remote participants and an option for all participants', () => {
  render(<RecipientSelector onRecipientSelected={jest.fn()} remoteParticipants={testRemoteParticipants} />)

  expect(screen.getByRole('combobox')).toBeInTheDocument()
  expect(screen.getByRole('option', { name: 'Everyone' })).toBeInTheDocument()
  expect(screen.getByRole('option', { name: 'Test Remote Participant 1' })).toBeInTheDocument()
  expect(screen.getByRole('option', { name: 'Test Remote Participant 2' })).toBeInTheDocument()
})

test('calls onRecipientSelected when a recipient is selected with the id of the recipient', () => {
  const mockRecipientSelectedHandler = jest.fn()
  render(
    <RecipientSelector onRecipientSelected={mockRecipientSelectedHandler} remoteParticipants={testRemoteParticipants} />
  )
  userEvent.selectOptions(
    screen.getByRole('combobox'),
    screen.getByRole('option', { name: 'Test Remote Participant 1' })
  )

  expect(mockRecipientSelectedHandler).toHaveBeenCalledTimes(1)
  expect(mockRecipientSelectedHandler).toHaveBeenCalledWith('testRemoteParticipantId1')
})

test('calls onRecipientSelected with empty string when the all participants option is selected', () => {
  const mockRecipientSelectedHandler = jest.fn()
  render(
    <RecipientSelector onRecipientSelected={mockRecipientSelectedHandler} remoteParticipants={testRemoteParticipants} />
  )
  userEvent.selectOptions(screen.getByRole('combobox'), screen.getByRole('option', { name: 'Everyone' }))

  expect(mockRecipientSelectedHandler).toHaveBeenCalledTimes(1)
  expect(mockRecipientSelectedHandler).toHaveBeenCalledWith(PUBLIC_CHAT_RECIPIENT)
})
