import { configureStore, EnhancedStore } from '@reduxjs/toolkit'
import { render, screen, waitFor } from '@testing-library/react'
import { Provider } from 'react-redux'
import React from 'react'
import { JoinPageRoomInput } from './JoinPageRoomInput'
import { zocksStoreConfig } from '../../../app/store'
import userEvent from '@testing-library/user-event'
import { JoinOptions } from '../../../store'

const renderWithState = async (store: EnhancedStore, joinAction: (joinOptions: JoinOptions) => void, props?: any) => {
  render(
    <Provider store={store}>
      <JoinPageRoomInput joinAction={joinAction} {...props} />
    </Provider>
  )
}

test('when joining fails error shows', async () => {
  const store = configureStore(zocksStoreConfig)
  const joinAction = jest.fn((joinOptions: JoinOptions) => {
    if (joinOptions.joinErrorCallback) {
      joinOptions.joinErrorCallback('test error')
    }
  })
  await renderWithState(store, joinAction)
  const roomIdInput = screen.getByLabelText('Enter a Meeting ID')
  userEvent.clear(roomIdInput)
  userEvent.type(roomIdInput, 'test room id')
  userEvent.click(screen.getByRole('button', { name: 'Join the Meeting' }))

  await waitFor(() => {
    expect(roomIdInput).toHaveClass('zocks__join-page__room-input--error')
  })
  expect(screen.getByText('test error')).toBeInTheDocument()
})

test('when joining fails custom error component shows', async () => {
  const store = configureStore(zocksStoreConfig)
  const joinAction = jest.fn((joinOptions: JoinOptions) => {
    if (joinOptions.joinErrorCallback) {
      joinOptions.joinErrorCallback('test error')
    }
  })

  const errorComponent = () => {
    return <div>Custom error component</div>
  }

  await renderWithState(store, joinAction, { components: { ErrorComponent: errorComponent } })
  const roomIdInput = screen.getByLabelText('Enter a Meeting ID')
  userEvent.clear(roomIdInput)
  userEvent.type(roomIdInput, 'test room id')
  userEvent.click(screen.getByRole('button', { name: 'Join the Meeting' }))

  await waitFor(() => {
    expect(roomIdInput).toHaveClass('zocks__join-page__room-input--error')
  })
  expect(screen.getByText('Custom error component')).toBeInTheDocument()
})
