import onFind from './dom/onFind'
import { announce } from './dom/aria'
import { toggleMenu } from './dom/popupMenu'
import Widget from './widget'

onFind('btu-widget.SearchWidget-moreFilters', (widget: Widget) => {
  const toggleTitle = () => {
    if (widget.collapsed) {
      widget.heading = widget.dataset.moreFiltersLabel
    } else {
      widget.heading = widget.dataset.lessFiltersLabel
    }
  }

  toggleTitle()

  widget.addEventListener('btu-widget-toggle', () => {
    toggleTitle()
  })
})

onFind('.SearchWidget.DashboardWidget', (element) => {
  const column = element.closest('.DashboardRow-column')
  column?.classList.add('is-search-widget')
})

// Open up the Dropdown and tether display.
onFind('.SavedSearches-more', (more) => {
  more.addEventListener('click', () => {
    const list = more.nextSibling
    toggleMenu(list, more)
  })
})

onFind('.SavedSearches-more-dropdown-delete', (element: HTMLElement) => {
  element.addEventListener('click', (e) => {
    if (element.dataset.deleted) announce(element.dataset.deleted)
  })
})

onFind('.SearchWidget-dateRangeSelect', (select: HTMLSelectElement) => {
  // Toggle additional inputs when date-time range search filter changes.
  const toggleRanges = (select: HTMLSelectElement) => {
    const c = select.value

    if (!select.parentNode) return
    const dateRanges = select.parentNode.querySelectorAll<HTMLElement>(
      '.SearchWidget-dateRange',
    )

    for (const range of dateRanges) {
      const hidden = c !== range.dataset.class
      range.hidden = hidden

      for (const input of range.querySelectorAll('input')) {
        input.disabled = hidden
      }
    }
  }

  toggleRanges(select)

  select.addEventListener('change', ({ target }) => {
    if (target instanceof HTMLSelectElement) toggleRanges(target)
  })
})

onFind('.SearchWidget-toolEntityFilterSelect', (select: HTMLSelectElement) => {
  const toggleToolEntitySelect = (select: HTMLSelectElement) => {
    if (!select.parentNode) return
    const c = select.value
    const dropdown = select.parentNode.querySelector<HTMLElement>(
      '.toolEntityDropdown-container',
    )

    if (!dropdown) return
    dropdown.hidden = c !== 'com.psddev.cms.ui.search.SelectToolEntityFilter'
  }

  toggleToolEntitySelect(select)

  select.addEventListener('change', ({ target }) => {
    if (target instanceof HTMLSelectElement) toggleToolEntitySelect(target)
  })
})

// Remove empty placeholder when not needed
onFind(
  '.SearchWidget-collections > .SearchWidget-filter:not(:last-child) > select',
  (select) => {
    if (!select.textContent) {
      if (select.parentNode instanceof HTMLElement) select.parentNode.remove()
    }
  },
)

onFind('.SearchWidget-reset', (resetBtn) => {
  resetBtn.addEventListener('click', () => {
    // TODO: TypeScript conversion - Replace jquery once popup.js is converted.
    if (!$(resetBtn).popup('source')) return
    const source: HTMLElement = ($(resetBtn) as any).popup('source')[0]
    if (source) {
      if (source instanceof HTMLAnchorElement) {
        const controls = resetBtn.closest('.SearchWidget-controls')
        if (controls) {
          const filters = controls.querySelector('form.searchFiltersRest')
          if (filters instanceof HTMLFormElement) {
            filters.reset()
          }
        }
        source.click()
      } else if (source instanceof HTMLFormElement) {
        source.reset()
        const resetInput = source.querySelector<HTMLInputElement>('[name="rf"]')
        const stInput = source.querySelector<HTMLInputElement>('[name="st"]')
        if (resetInput) resetInput.value = 'true'
        source.requestSubmit()
        if (resetInput) resetInput.value = 'false'
        if (stInput) stInput.value = ''
      }
    }
    return false
  })
})

onFind('.searchFiltersType', (element) => {
  element.addEventListener('change', () => {
    const targetInput = element
      .closest('.Page')
      ?.querySelector('form.Page-search input[name="st"]')
    const searchType = element.querySelector('select[name="st"]')

    if (!targetInput || !searchType) return
    if (
      !(targetInput instanceof HTMLInputElement) ||
      !(searchType instanceof HTMLSelectElement)
    )
      return

    targetInput.value = searchType.value
  })

  // Set the search 'q' input value to possible saved sticky value.
  const sourceQuery = element.querySelector('input[name="q"]')
  if (!sourceQuery || !(sourceQuery instanceof HTMLInputElement)) return

  const targetQuery = element.closest('.Popup[name="miscSearch"]')
    ? document.querySelector('.Page-search input[name="q"]')
    : element.nextElementSibling?.querySelector('input[name="q"]')

  if (targetQuery && targetQuery instanceof HTMLInputElement) {
    targetQuery.value = sourceQuery.value
  }
})
