import PropTypes from 'prop-types';
import React, { Fragment, useContext, useEffect, useState } from 'react';
import { NavLink, withRouter } from 'react-router-dom';
import { Collapse, Nav, NavItem, NavLink as BootstrapNavLink } from 'reactstrap';
import AppContext from '../../context/Context';
import NavbarVerticalMenuItem from './NavbarVerticalMenuItem';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';

const NavbarVerticalMenu = ({ routes, location }) => {
  const { setShowBurgerMenu } = useContext(AppContext);
  const [ navRoutes, setNavRoutes ] = useState([])

  useEffect(() => {
    let navs = []
    routes.forEach((route, index) => {
      navs.push({ ...route, isOpened: true, index })
    });
    setNavRoutes(navs)
  }, []);

  const toggleOpened = (e, route) => {
    e.preventDefault();
    const clickedNav = navRoutes.find(r => r.index === route.index)
    const toggled = {...clickedNav, isOpened: !route.isOpened}
    setNavRoutes(prev => prev.map(navRoute => navRoute.index === toggled.index ? toggled : navRoute))
  };

  const getHr = name => {
    if (name === 'Widgets' || name === 'Documentation') {
      return (
        <div className="navbar-vertical-divider">
          <hr className="navbar-vertical-hr my-2" />
        </div>
      );
    }
  };

  return navRoutes.map((route) => {
    const { isOpened, ...routeRest } = route; //remove isOpened attribute from the route abject
    if (!route.children) {
      return (
        <Fragment key={route.index}>
          {getHr(route.name)}
          <NavItem>
            <NavLink className="nav-link" {...routeRest} onClick={() => setShowBurgerMenu(false)}>
              <NavbarVerticalMenuItem route={routeRest} />
            </NavLink>
          </NavItem>
        </Fragment>
      );
    }
    return (
      <Fragment key={route.index}>
        {getHr(route.name)}
        <NavItem>
          <BootstrapNavLink
            onClick={e => toggleOpened(e, route)}
            className="dropdown-indicator cursor-pointer"
            aria-expanded={route.isOpened}
          >
            <NavbarVerticalMenuItem route={routeRest} />
          </BootstrapNavLink>
          <Collapse isOpen={route.isOpened}>
            <Nav>
              <NavbarVerticalMenu routes={route.children} location={location} />
            </Nav>
          </Collapse>
        </NavItem>
      </Fragment>
    );
  })
};

NavbarVerticalMenu.propTypes = {
  routes: PropTypes.array.isRequired,
  location: PropTypes.object.isRequired
};

export default withRouter(NavbarVerticalMenu);
