import React, { FC, useState } from 'react'
import { Link } from 'react-router-dom'
import { useSelector } from 'react-redux'
import classNames from 'classnames'
import { Collapse, Nav, NavItem, NavLink } from 'reactstrap'
import { FeatherIcon } from '../../../components/FeatherIcons'
import { IMenuItem, IReduxState, ISubMenuItem } from '../../../interfaces'
import style from './scss/style.module.scss'

interface ISubMenu {
  icon?: string,
  title: string,
  items: ISubMenuItem []
}

const SubMenu : FC<ISubMenu> = (props: ISubMenu) => {
  const { icon, title, items } = props

  const [collapsed, setCollapsed] = useState(true)
  const toggle = () => setCollapsed(!collapsed)
 
  return (
    <div>
      <NavItem onClick={toggle} className={classNames(style.navitem, !collapsed ? style.menuopen : '')}>
        <NavLink className={classNames("dropdown-toggle", `${style.navlink}`)}>
          {icon ? <FeatherIcon icon={icon}/> : ''}
          <span className={style.linktitle}>{title}</span>
        </NavLink>
      </NavItem>
      <Collapse isOpen={!collapsed} navbar className={classNames(`${style.itemsmenu}`, { "mb-1": !collapsed })}>
        {items.map((item: ISubMenuItem, index: number) => (
          <NavItem key={index} className={classNames(style.navitem, "pl-4")}>
            <NavLink tag={Link} to={item.target} className={style.navlink}>
              {item.icon ? <FeatherIcon icon={item.icon}/> : ''}
              <span className={style.linktitle}>{item.title}</span>
            </NavLink>
          </NavItem>
        ))}
      </Collapse>
    </div>
  )
}

const SideMenu : FC = () => {
  let { sideMenu = [] } = useSelector((state: IReduxState) => state.settings)

  return <div className={style.sidemenu}>
    <Nav vertical className="list-unstyled pb-3">
      {sideMenu.map((item: IMenuItem, index: number) => {
        if(item.items) {
          return <SubMenu key={index} icon={item.icon} title={item.title} items={item.items} />
        }
      
        return <NavItem key={index} className={style.navitem}>
          <NavLink tag={Link} to={item.target} className={style.navlink}>
            {item.icon ? <FeatherIcon icon={item.icon}/> : ''}
            <span className={style.linktitle}>{item.title}</span>
          </NavLink>
        </NavItem>
      })}
    </Nav>
  </div>
}

export {
  SideMenu
}
