// @flow
/* eslint react/prop-types: 0 */
import React from 'react'
import { WrapperMenu } from './Wrappers'
import MenuItemComponent from './MenuItemComponent'
import MenuDropdownComponent from './MenuDropdownComponent'

export type MenuOptionT = {
  label: string,
  onClick: Function
}

type MenuItemT = {
  label: string,
  active?: boolean,
  onClick?: Function,
  dropdownMenuElements: MenuOptionT[]
}

type Props = {
  role?: string,
  className?: string,
  menuItems: MenuItemT[]
}

type State = {
  activeStatus: boolean[]
}

class NavbarMenu extends React.Component<Props, State> {
  state: State = {
    activeStatus: this.props.menuItems.map(menuItem => menuItem.active || false)
  }

  setActiveStatus = (index: number) => () => {
    const newActiveStatus = this.state.activeStatus.map(() => false)
    newActiveStatus[index] = true

    this.setState({ activeStatus: newActiveStatus })

    if (this.props.menuItems[index].onClick) {
      this.props.menuItems[index].onClick()
    }
  }

  render() {
    const { menuItems, role, className } = this.props

    return (
      <WrapperMenu role={role} className={className}>
        {menuItems.map(
          (menuItem, indexTab) =>
            menuItem.dropdownMenuElements ? (
              <MenuDropdownComponent
                key={`navbar-menu-item-dropdown-${menuItem.label}`}
                active={this.state.activeStatus[indexTab]}
                onClick={this.setActiveStatus(indexTab)}
                label={menuItem.label}
                dropdownMenuElements={menuItem.dropdownMenuElements}
              />
            ) : (
              <MenuItemComponent
                key={`navbar-menu-item-${menuItem.label}`}
                active={this.state.activeStatus[indexTab]}
                onClick={this.setActiveStatus(indexTab)}
                label={menuItem.label}
              />
            )
        )}
      </WrapperMenu>
    )
  }
}

export default NavbarMenu
