import ReactTestUtils from 'react-dom/test-utils'
import Button from '@instructure/ui-buttons/lib/components/Button'
import { ADD_TO_BANK_MODAL } from '@instructure/quiz-common/lib/constants'
import AddToBankOptions from '../index'

describe('AddToBankOptions', () => {
  const sandbox = sinon.createSandbox()
  const openModalStub = sandbox.stub()
  const screenreaderNotificationStub = sandbox.stub()
  const showErrorStub = sandbox.stub()

  afterEach(() => {
    sandbox.resetHistory()
  })

  const guid = '12345'

  const defaultProps = {
    displayPosition: 1,
    entryType: 'Item',
    guid,
    isValid: true,
    openModal: openModalStub,
    screenreaderNotification: screenreaderNotificationStub,
    showError: showErrorStub
  }

  const testbed = createTestbed(AddToBankOptions, defaultProps)

  const clickButton = () => {
    const button = testbed.findChildByType(Button)
    const buttonNode = testbed.findChildrenByTagName('button', button)[0]
    ReactTestUtils.Simulate.click(buttonNode)
  }

  it('renders a button with the correct text', () => {
    testbed.render()

    const button = testbed.findChildByType(Button)
    expect(button).to.not.be.undefined()

    const text = testbed.getText()
    expect(text).to.include('Add to Bank')
  })

  describe('opening bank', () => {
    context('with valid entry', () => {
      it('calls openModal with the correct props', () => {
        testbed.render()
        clickButton()

        expect(
          openModalStub.calledWith(
            [
              ADD_TO_BANK_MODAL, 'Item', guid
            ].join(':')
          )
        ).to.be.true()
      })
    })

    context('with invalid entry', () => {
      it('calls screenreaderNotification with the expected message', () => {
        testbed.render({isValid: false})

        clickButton()

        const expectedMsg = 'Item 1 cannot be saved due to invalid input data.'

        expect(openModalStub).not.to.have.been.called()
        expect(
          screenreaderNotificationStub.calledWith(expectedMsg)
        ).to.be.true()
      })

      it('calls showError with the guid', () => {
        testbed.render({isValid: false})

        clickButton()

        expect(openModalStub).not.to.have.been.called()
        expect(showErrorStub.calledWith(guid)).to.be.true()
      })
    })
  })
})
