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

const renderWithState = async (
  store: EnhancedStore,
  joinAction: (joinOptions: JoinOptions) => void,
  props?: any,
  authActions: ZocksAuthActions = { hasScope: jest.fn().mockReturnValue(true) }
) => {
  render(
    <Provider store={store}>
      <JoinPageRoomButtons joinAction={joinAction} authActions={authActions} {...props} />
    </Provider>
  )
}

test('when start new meeting 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)
  userEvent.click(screen.getByRole('button', { name: 'Start New Meeting' }))

  expect(screen.getByText('test error')).toBeInTheDocument()
})

test('when start new meeting 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 } })

  userEvent.click(screen.getByRole('button', { name: 'Start New Meeting' }))

  expect(screen.getByText('Custom error component')).toBeInTheDocument()
})
