import { setupMediaDevicesMock } from '../../testUtils'
import { configureStore, EnhancedStore } from '@reduxjs/toolkit'
import { render, screen } from '@testing-library/react'
import { Provider } from 'react-redux'
import { ConnectionTester } from './ConnectionTester'
import { zocksStoreConfig } from '../../app/store'
import { defaultTokenKey } from '@zocks-communications/client-sdk-js'
import userEvent from '@testing-library/user-event'

beforeEach(() => setupMediaDevicesMock())

const renderWithState = async (store: EnhancedStore) => {
  render(
    <Provider store={store}>
      <ConnectionTester />
    </Provider>
  )
  expect(await screen.findByRole('button', { name: 'Start Test' })).toBeInTheDocument()
}

test('renders with default name when room id is not given', async () => {
  const store = configureStore(zocksStoreConfig)
  await renderWithState(store)

  expect(screen.getByRole('textbox', { name: 'Test room' })).toHaveValue('connection-tester')
  expect(screen.getByRole('combobox', { name: 'Room type' })).toHaveValue('name')
  expect(screen.getByRole('radio', { name: 'Use my token' })).toBeChecked()
  expect(screen.getByRole('radio', { name: 'Use other token' })).not.toBeChecked()
  expect(screen.getByRole('button', { name: 'Start Test' })).toBeInTheDocument()
})

test('renders with id if room id is given', async () => {
  const store = configureStore(zocksStoreConfig)
  render(
    <Provider store={store}>
      <ConnectionTester roomId='roomId' />
    </Provider>
  )

  expect(screen.getByRole('textbox', { name: 'Test room' })).toHaveValue('roomId')
  expect(screen.getByRole('combobox', { name: 'Room type' })).toHaveValue('id')
  expect(screen.getByRole('radio', { name: 'Use my token' })).toBeChecked()
  expect(screen.getByRole('radio', { name: 'Use other token' })).not.toBeChecked()
  expect(screen.getByRole('button', { name: 'Start Test' })).toBeInTheDocument()
})

test('Shows token input if other token radio button is selected', async () => {
  global.localStorage.setItem(defaultTokenKey, 'local')
  const store = configureStore(zocksStoreConfig)
  await renderWithState(store)

  expect(screen.getByRole('radio', { name: 'Use my token' })).toBeChecked()
  expect(screen.queryByTestId('token')).not.toBeInTheDocument()
  const otherTokenRadio = screen.getByRole('radio', { name: 'Use other token' })
  userEvent.click(otherTokenRadio)

  expect(screen.getByTestId('token')).toBeInTheDocument()
})
