import create from './dom/create'
import insertLast from './dom/insertLast'
import onFind from './dom/onFind'
import onRemove from './dom/onRemove'

// Allow user to move items to/from Visible Items list and
// Hidden Items list by clicking on the area around the chevron icon.
onFind(
  '.CIG[data-type="com.psddev.cms.db.ContentForm"]',
  (form: HTMLElement) => {
    const visibleItems = form.querySelector<HTMLOListElement>(
      ':scope .CIG-row[data-field="visibleFields"] ol',
    )
    const hiddenItems = form.querySelector<HTMLOListElement>(
      ':scope .CIG-row[data-field="hiddenItems"] ol',
    )
    const items = form.querySelectorAll<HTMLLIElement>(
      ':scope li[data-sortable-item-type',
    )
    const tooltips = window.BRIGHTSPOT?.ui.tooltips

    items.forEach((item) => {
      const buttonWrapper = create('div', {
        className: 'RCIG-toggleButtonWrapper',
      })
      const button = create('button', {
        className: 'RCIG-toggleButton',
      })

      buttonWrapper.appendChild(button)
      insertLast(buttonWrapper, item)

      button.title = button.closest('.CIG-row[data-field="visibleFields"]')
        ? tooltips.itemHide
        : tooltips.itemShow
    })

    const buttons = form.querySelectorAll<HTMLElement>(
      ':scope .RCIG-toggleButtonWrapper',
    )
    buttons.forEach((button) => {
      button.addEventListener('click', (event) => {
        event.preventDefault()

        const toHide = button.closest('.CIG-row[data-field="visibleFields"]')

        const childEl = button.firstChild
        if (childEl instanceof HTMLElement)
          childEl.title = toHide ? tooltips.itemShow : tooltips.itemHide

        const oldInputName =
          button.closest<HTMLOListElement>('.Sortable')?.dataset
            .sortableInputName
        const newInputName = toHide
          ? hiddenItems?.dataset.sortableInputName
          : visibleItems?.dataset.sortableInputName

        const pendingItem = button.closest('li')
        if (!pendingItem) return

        pendingItem
          .querySelectorAll(`:scope [name^="${oldInputName}"]`)
          .forEach((input) => {
            const name = input.getAttribute('name')
            if (!oldInputName || !newInputName || !name) {
              return
            } else {
              input.setAttribute(
                'name',
                name.replace(oldInputName, newInputName),
              )
            }
          })

        onRemove.pause()

        if (toHide) {
          hiddenItems?.appendChild(pendingItem)
        } else {
          visibleItems?.appendChild(pendingItem)
        }

        requestAnimationFrame(() => onRemove.resume())
      })
    })

    // Update tooltips on drag/drop
    hiddenItems?.addEventListener('add', (evt) => {
      const e = evt as Event & Record<'item', unknown>
      if (e.item instanceof HTMLElement) {
        const button = e.item.querySelector(':scope .RCIG-toggleButton')
        if (button instanceof HTMLElement) button.title = tooltips.itemShow
      }
    })

    visibleItems?.addEventListener('add', (evt) => {
      const e = evt as Event & Record<'item', unknown>
      if (e.item instanceof HTMLElement) {
        const button = e.item.querySelector(':scope .RCIG-toggleButton')
        if (button instanceof HTMLElement) button.title = tooltips.itemHide
      }
    })
  },
)
