import React from 'react'
import { Provider } from 'react-redux'
import { configureStore } from '@reduxjs/toolkit'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { zocksStoreConfig } from '../../../app/store'
import { changeParticipantsView, ParticipantsViewType } from '../../../store'
import { ViewSwitcher } from './ViewSwitcher'

afterEach(() => {
  jest.restoreAllMocks()
})

const renderWithState = (view: ParticipantsViewType) => {
  const store = configureStore(zocksStoreConfig)
  store.dispatch(changeParticipantsView(view))
  render(
    <Provider store={store}>
      <ViewSwitcher />
    </Provider>
  )
}

test('renders a change to grid and change to speaker view button', () => {
  renderWithState(ParticipantsViewType.Grid)

  expect(screen.getByRole('button', { name: 'Change to grid view' })).toBeInTheDocument()
  expect(screen.getByRole('button', { name: 'Change to speaker view' })).toBeInTheDocument()
})

test('the change to grid view button is disabled when the current view is grid', () => {
  renderWithState(ParticipantsViewType.Grid)

  expect(screen.getByRole('button', { name: 'Change to grid view' })).toBeDisabled()
  expect(screen.getByRole('button', { name: 'Change to speaker view' })).not.toBeDisabled()
})

test('the change to speaker view button is disabled when the current view is speaker', () => {
  renderWithState(ParticipantsViewType.Speaker)

  expect(screen.getByRole('button', { name: 'Change to speaker view' })).toBeDisabled()
  expect(screen.getByRole('button', { name: 'Change to grid view' })).not.toBeDisabled()
})

test('changes to speaker view when the change to speaker view button is clicked', () => {
  renderWithState(ParticipantsViewType.Grid)

  const gridViewButton = screen.getByRole('button', { name: 'Change to grid view' })
  const speakerViewButton = screen.getByRole('button', { name: 'Change to speaker view' })
  userEvent.click(speakerViewButton)

  expect(speakerViewButton).toBeDisabled()
  expect(gridViewButton).not.toBeDisabled()
})

test('changes to grid view when the change to grid view button is clicked', () => {
  renderWithState(ParticipantsViewType.Speaker)

  const gridViewButton = screen.getByRole('button', { name: 'Change to grid view' })
  const speakerViewButton = screen.getByRole('button', { name: 'Change to speaker view' })
  userEvent.click(gridViewButton)

  expect(gridViewButton).toBeDisabled()
  expect(speakerViewButton).not.toBeDisabled()
})
