import Cookies from 'js-cookie'
import create from './dom/create'
import onFind from './dom/onFind'
type DiffFormPostFields = 'left' | 'right'

interface DiffFormPostData extends FormData {
  append(
    name: DiffFormPostFields,
    value: string | Blob,
    fileName?: string,
  ): void
}

// Closes Diff popup when clicking title
onFind('.Diff-title', (element: HTMLElement) => {
  element.focus()
  element.addEventListener('click', () => {
    element
      .closest<HTMLElement>('.Popup-content')
      ?.querySelector<HTMLElement>('.Popup-close')
      ?.click()
  })
})

// Rich Text Element Diff Popup
onFind('[data-diff-state-id]', (element: HTMLElement) => {
  const id = element.dataset.diffStateId
  const container = element.closest<HTMLElement>('.Diff-container')
  const diffs = container?.querySelectorAll<HTMLElement>(
    `[data-diff-state-id="${id}"]`,
  )

  if (diffs?.length) {
    const diffsLeft = diffs[0]
    const diffsRight = diffs[1]
    const diffsLeftDataset = diffsLeft?.dataset
    const diffsRightDataset = diffsRight?.dataset
    const diffLeftState = diffsLeftDataset?.diffState
    const diffRightState = diffsRightDataset?.diffState

    // If the diff pair does not exist remove the attribute from the existing one
    if (!diffLeftState) {
      diffs[1]?.removeAttribute('data-diff-state')
      return
    } else if (!diffRightState) {
      diffs[0]?.removeAttribute('data-diff-state')
      return
    }

    element.addEventListener('click', async (evt) => {
      // Closing the diff popup if one is already open to prevent close button weirdness
      $('.is-diff').popup('close')
      // If one side has no change the diffs array value can be undefined.  We are checking for that here.
      const headers = new Headers()
      const cookie = Cookies.get('bsp.csrf')

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

      const body: DiffFormPostData = new FormData()
      body.append('left', diffLeftState)
      body.append('right', diffRightState)

      try {
        const response = await fetch('/cms/diffRevision', {
          method: 'POST',
          headers,
          body,
        })
        const itemHtml = await response.text()

        document.getElementById('rtediff')?.remove()

        const container = create('div')
        container.id = 'rtediff'
        document.body.appendChild(container)
        container.innerHTML = itemHtml

        const jqueryContainer = $(container).popup()
        // Attaching marker class to popup for cleanup if the user clicks on a clickable diff field
        jqueryContainer.popup('container').addClass('is-diff')
        jqueryContainer.popup('open')
      } catch (err) {
        console.error(err)
      }
    })
  }
})
