// @flow
/* eslint react/prop-types: 0 */
import React from 'react'
import type { MenuItemComponentProps } from './MenuItemComponent'
import type { MenuOptionT } from './index'
import {
  WrapperMenuItem,
  MenuItem,
  MenuOption,
  Caret,
  WrapperMenuDropdown
} from './Wrappers'

type Props = MenuItemComponentProps & {
  dropdownMenuElements: MenuOptionT[]
}

type State = {
  open: boolean
}

class MenuDropdownComponent extends React.Component<Props, State> {
  state: State = {
    open: false
  }

  toggleDisplayDropwdown = () => {
    this.setState({ open: !this.state.open })
  }

  handleClickMenuOption = (index: number) => () => {
    this.toggleDisplayDropwdown()
    this.props.onClick()
    this.props.dropdownMenuElements[index].onClick()
  }

  render() {
    const { active, label, dropdownMenuElements } = this.props

    return (
      <WrapperMenuItem active={active} float="left">
        <MenuItem onClick={this.toggleDisplayDropwdown}>
          {label}
          <Caret />
        </MenuItem>
        <WrapperMenuDropdown visible={this.state.open}>
          {dropdownMenuElements.map((menuOption, optionIndex) => (
            <WrapperMenuItem
              key={`navbar-menu-option-dropdown-${menuOption.label}`}
              active={false}
            >
              <MenuOption onClick={this.handleClickMenuOption(optionIndex)}>
                {menuOption.label}
              </MenuOption>
            </WrapperMenuItem>
          ))}
        </WrapperMenuDropdown>
      </WrapperMenuItem>
    )
  }
}

export default MenuDropdownComponent
