import * as React from 'react'
import classNames from 'classnames'

export type ChildrenProps = Readonly<{
  name: string
}>

export type Props = Readonly<{
  open: boolean
  right: boolean
  beside: boolean
  children: (showDropdown: any, hideDropdown: any, isOpen: boolean) => any
}>

type State = Readonly<{
  open: boolean
}>

export default class ButtonDropdown extends React.Component<Props, State> {
  static defaultProps: Props = {
    open: false,
    right: false,
    beside: false,
    children: () => {},
  }

  constructor(props: Props) {
    super(props)
    this.state = {
      open: props.open,
    }
  }

  showDropdown = (e: React.SyntheticEvent) => {
    if (e && e.preventDefault) e.preventDefault()
    this.setState({ open: true })
  }

  hideDropdown = (e: React.SyntheticEvent) => {
    if (e && e.preventDefault) e.preventDefault()
    setTimeout(() => this.setState({ open: false }), 100)
  }

  render() {
    const { right, beside, children } = this.props
    const { open } = this.state
    const dropdownClasses: string = classNames(
      'ui-dropdown ui-display--inline-block ui-position--relative',
      {
        'ui-dropdown--open': open,
        'ui-dropdown--beside': beside,
        'ui-dropdown--rtl': right,
      }
    )

    return (
      <div className={dropdownClasses} {...this.props}>
        {children(this.showDropdown, this.hideDropdown, open)}
      </div>
    )
  }
}
