import onFind from './dom/onFind'
import storage from './util/storage'

type SearchControlsToggleState = 'EXPANDED' | 'COLLAPSED' | null

const setToggleState = (
  widget: HTMLDivElement,
  val: SearchControlsToggleState,
) => {
  const widgetName = widget.getAttribute('name')
  if (widgetName === null) return

  const storageKey =
    'BSP.v5.SearchWidget' + '/' + widgetName + '/' + 'controls.toggle'

  if (val !== null) {
    storage.set(storageKey, val)
  }
}

const getToggleState = (widget: HTMLDivElement) => {
  const widgetName = widget.getAttribute('name')
  if (widgetName === null) return null

  const storageKey =
    'BSP.v5.SearchWidget' + '/' + widgetName + '/' + 'controls.toggle'

  return storage.get(storageKey) as SearchControlsToggleState
}

export const toggle = (
  widget: HTMLDivElement,
  forcedVal?: SearchControlsToggleState,
) => {
  if (forcedVal !== undefined) {
    setToggleState(widget, forcedVal)
  } else {
    setToggleState(
      widget,
      getToggleState(widget) === 'EXPANDED' ? 'COLLAPSED' : 'EXPANDED',
    )
  }

  // Broadcast a layout update.
  // Used primarily by the board results view to reflow the cards/cols.
  window.dispatchEvent(new Event('resize'))
  update(widget)

  const toggleButton = widget.querySelector<HTMLButtonElement>(
    '.SearchWidget-controlsToggle',
  )
  if (toggleButton) {
    toggleButton.ariaExpanded =
      getToggleState(widget) === 'EXPANDED' ? 'true' : 'false'
  }
}

const update = (widget: HTMLDivElement) => {
  const lastToggleState = getToggleState(widget)
  // Update with last state if it exists.
  if (lastToggleState !== null) {
    if (lastToggleState === 'EXPANDED') {
      widget.classList.remove('filters-collapsed--v5')
    } else {
      widget.classList.add('filters-collapsed--v5')
    }
  } else {
    toggle(widget, 'EXPANDED')
  }
}

onFind('.SearchWidget', (widget: HTMLDivElement) => {
  update(widget)
})

onFind('.SearchWidget-controlsToggle', (button: HTMLButtonElement) => {
  const widget = button.closest('.SearchWidget, .SearchPage') as HTMLDivElement
  if (widget === null) return

  button.ariaExpanded = getToggleState(widget) === 'EXPANDED' ? 'true' : 'false'

  // Collapse the search filters on mobile by default.
  if (window.matchMedia('(max-width: 768px)').matches) {
    toggle(widget, 'COLLAPSED')
  }

  button.addEventListener('click', () => {
    toggle(widget)
  })
})
