import onFind from './dom/onFind'
import create from './dom/create'
import Cookies from 'js-cookie'
import Tether from './dom/Tether'
import getZindex from './main/webapp/script/v3/plugin/popup'

onFind('.BulkWorkflow-button', (button: HTMLElement) => {
  let workflowActions: HTMLElement | null = null

  button.addEventListener('keydown', (event) => {
    if (event.key === 'Enter' || event.key === ' ') {
      event.preventDefault()
      button.click()
    }
  })

  button.addEventListener('click', async (event) => {
    event.preventDefault()
    event.stopPropagation()

    const target = event.target
    let url

    if (target instanceof HTMLElement) {
      url = target.getAttribute('action-url')
    }

    if (!url) {
      return
    }

    if (!workflowActions) {
      const headers = new Headers()
      const cookie = Cookies.get('bsp.csrf')

      if (cookie) {
        headers.append('Brightspot-CSRF', cookie)
      }

      const response = await fetch(url, { headers })

      const body = await response.text()

      workflowActions = create('div', {
        className: 'BulkWorkflow',
        innerHTML: body,
        role: 'dialog',
        'aria-modal': 'true',
      })

      document.body.appendChild(workflowActions)

      workflowActions.addEventListener('keydown', (e) => {
        if (e.key === 'Escape') {
          e.stopPropagation()

          const closeButton =
            workflowActions?.querySelector<HTMLElement>('.closeButton')
          if (closeButton) {
            closeButton.click()
          }
        }
      })
    }

    const popup = button.closest('.Popup')
    if (popup) {
      workflowActions.style.zIndex = getZindex().toString()
    }

    Tether.toggle(button, workflowActions, () => {
      const isOpen = button.classList.toggle('is-open')
      workflowActions?.classList.toggle('is-open')

      if (isOpen) {
        requestAnimationFrame(() => {
          const firstFocusableElement =
            workflowActions?.querySelector<HTMLElement>('.closeButton')
          if (firstFocusableElement) {
            firstFocusableElement.focus()
          }
        })
      }
      return isOpen
    })

    const closeButton =
      workflowActions.querySelector<HTMLElement>('.closeButton')

    closeButton?.addEventListener('click', () => {
      const t = Tether.toggles.get(button)

      if (t && t.closeListener) {
        window.removeEventListener('click', t.closeListener, true)
      }

      button.classList.remove('is-open')
      workflowActions?.classList.remove('is-open')
      workflowActions?.remove()
      workflowActions = null

      const searchToggle = button
        .closest('.SearchResult')
        ?.querySelector<HTMLElement>('.SearchResult-actions-toggle')
      if (searchToggle) {
        searchToggle.focus()
      }
    })
  })
})
