import { className } from 'lib/css'
import { ComponentChildren } from 'preact'
import { useRef, useState } from 'preact/hooks'
import type { FramePosition } from 'ui/components/options/options-frame'
import InOutTransition, {
  transitionStartStates,
} from 'ui/components/widgets/in-out-transition'
import { useGeneratedId } from 'ui/hooks/seamly-hooks'
import { focusElement, getKey, keyNames } from 'ui/utils/general-utils'
import TranslationsOptionsDialog from './options-dialog'

type TranslationsOptionsButtonProps = {
  children: ComponentChildren
  position?: FramePosition
  classNames?: string[]
}

export default function TranslationsOptionsButton({
  children,
  position = {
    horizontal: 'left',
    vertical: 'top',
  },
  classNames = [],
}: TranslationsOptionsButtonProps) {
  const [menuIsOpen, setMenuIsOpen] = useState(false)
  const toggleButton = useRef(null)
  const toggleButtonId = useGeneratedId()

  const onMainKeyDownHandler = (e: KeyboardEvent) => {
    if (!menuIsOpen) {
      return
    }

    if (getKey(e) === keyNames.Escape) {
      setMenuIsOpen(false)
      focusElement(toggleButton.current)
    }
  }

  const handleDialogClose = () => {
    setMenuIsOpen(false)
  }

  const handleToggleClick = () => {
    setMenuIsOpen(!menuIsOpen)
  }

  const handleToggleKeyDown = (e: KeyboardEvent) => {
    if (getKey(e) === keyNames.ArrowDown) {
      setMenuIsOpen(true)
      e.preventDefault()
    }
  }
  return (
    <div
      className={className('translations__container')}
      onKeyDown={onMainKeyDownHandler}
    >
      <InOutTransition
        transitionStartState={transitionStartStates.notRendered}
        isActive={menuIsOpen}
      >
        <div className={className('options__dialog')} role="dialog">
          <TranslationsOptionsDialog
            onClose={handleDialogClose}
            position={position}
          />
        </div>
      </InOutTransition>
      <button
        type="button"
        className={className([
          'button',
          'chat__options__button',
          ...classNames,
        ])}
        id={toggleButtonId}
        onClick={handleToggleClick}
        onKeyDown={handleToggleKeyDown}
        ref={toggleButton}
        aria-haspopup="dialog"
        aria-expanded={menuIsOpen}
      >
        {children}
      </button>
    </div>
  )
}
