import ReactTestUtils from 'react-dom/test-utils'
import Popover from '@instructure/ui-overlays/lib/components/Popover'
import AddContentPopover from '../presenter'

import { DELETED_QUIZ_ENTRY } from '@instructure/quiz-common/lib/constants'

describe('AddContentPopover', () => {
  const switchOffEditingStub = sinon.stub()
  const switchOnEditingStub = sinon.stub()
  const clearUiStub = sinon.stub()
  const openAddContentModalStub = sinon.stub()

  const defaultProps = {
    allowStimulusCreation: true,
    appContainer: '#app',
    clearUi: clearUiStub,
    isEditing: true,
    isMobile: false,
    openAddContentModal: openAddContentModalStub,
    parentEntryId: 'parent123',
    position: 5,
    quizId: 'quiz123',
    shouldFocus: false,
    stimulusId: 'stimulus123',
    switchOffEditing: switchOffEditingStub,
    switchOnEditing: switchOnEditingStub,
    useStimulusTrigger: true
  }

  const testbed = createTestbed(withContext(AddContentPopover), defaultProps)
  let clock

  beforeEach(() => {
    switchOffEditingStub.resetHistory()
    switchOnEditingStub.resetHistory()
    clearUiStub.resetHistory()
    openAddContentModalStub.resetHistory()
  })

  afterEach(() => {
    if (clock) {
      clock.restore()
      clock = null
    }
  })

  it('renders a popover when not on mobile', () => {
    testbed.render()
    const popover = testbed.findChildByType(Popover)
    expect(popover).to.exist()
  })

  it('renders an open modal button when on mobile', () => {
    testbed.render({isMobile: true})
    const popover = testbed.findChildrenByType(Popover)[0]
    expect(popover).to.not.exist()

    const button = testbed.findChildByTagName('button')
    ReactTestUtils.Simulate.click(button)
    expect(openAddContentModalStub.called).to.be.true()
    const args = openAddContentModalStub.firstCall.args
    expect(args[0]).to.eql({
      allowStimulusCreation: defaultProps.allowStimulusCreation,
      parentEntryId: defaultProps.parentEntryId,
      position: defaultProps.position,
      quizId: defaultProps.quizId,
      stimulusId: defaultProps.stimulusId
    })
  })

  it('focuses correctly', () => {
    clock = sinon.useFakeTimers()
    testbed.render()
    testbed.render({shouldFocus: true})
    clock.tick(200)
    expect(clearUiStub.calledWith(DELETED_QUIZ_ENTRY)).to.be.true()
    expect(document.activeElement.innerText).to.eq('Attach Question')
  })

  describe('test with connect', () => {
    shouldRenderComponent(
      testbed, {}, AddContentPopover
    )
  })

  describe('a11y tests', () => {
    it('should meet a11y standards', (done) => {
      testbed.render()
      testbed.checkA11yStandards(done)
    })
  })
})
