import { useMemo, useState, useEffect } from 'preact/hooks'
import { Button } from '../atoms/button.js'
import { Menu } from '../atoms/menu.js'
import { NavLink } from '../atoms/nav-link.js'
import { ValidationError } from '../routing/error-handler.js'
import h from '../shared/h.js'
import markSelection from '../shared/mark-selection.js'
import splitLinks from '../shared/split-links.js'

export function Topbar ({ _model, _variant, ...props }) {
  const { links } = _model
  if (links.length === 0) {
    throw new ValidationError()
  }

  const [mainLinks, sideLinks] = useMemo(() => splitLinks(links), [links])
  markSelection(mainLinks)
  const left = _variant === 'left' || Boolean(sideLinks)

  return h('div', {
    ...props,
    className: 'w-full bg-bga text-txa',
    children: h('div', { className: 'm-auto max-w-page flex', role: 'list' },
      h(MainLinks, { links: mainLinks, left }),
      sideLinks && h(SideLinks, { links: sideLinks })
    )
  })
}

function MainLinks ({ links, left = false }) {
  return [
    !left && h('div', { className: 'grow' }),
    h('div', { className: 'flex' },
      links.map(link => h('div', { className: left ? 'grow-0 text-sm' : 'grow-0', role: 'listitem' },
        h(NavLink, { _model: link, _selection: 'top' })
      ))
    )
  ]
}

function SideLinks ({ links }) {
  const [isExpanded, setExpanded] = useState(false)

  useEffect(() => {
    const handler = () => setExpanded(false)
    globalThis.addEventListener('route', handler)
    return () => globalThis.removeEventListener('route', handler)
  }, [])

  if (!links || links.length === 0) {
    return null
  }

  const moreThanOne = links.length > 1
  const onKeyUp = event => event.key.startsWith('Esc') && setExpanded(false)

  return [
    h('div', { className: 'grow' }),
    h('div', { className: 'grow-0 flex items-center h-12 relative px-1', onKeyUp },
      !moreThanOne && h(Button, { _model: links[0], _size: 'xs' }),
      moreThanOne && [
        h(Button, {
          _expanded: isExpanded,
          _model: { ...links[0], value: undefined },
          _size: 'xs',
          onClick (event) {
            event.preventDefault()
            setExpanded(expanded => !expanded)
          }
        }),
        isExpanded && h(Menu, { role: 'list', style: 'top: calc(100% + 8px); inset-inline-end: 4px' },
          h('div', { className: 'py-1' },
            links.slice(1).map(link =>
              h('div', { role: 'listitem' },
                h(NavLink, { _model: link, _selection: 'right' })
              )
            )
          )
        )
      ]
    )
  ]
}
