import React, { FC, useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { useSelector } from 'react-redux'
import { Collapse, Navbar, NavbarBrand, NavbarToggler, NavItem, NavLink } from 'reactstrap'
import { FeatherIcon } from '../../../components/FeatherIcons'
import { ApplicationState } from '../../../store'
import { MenuItemModel } from '../../../models'


const NavMenu : FC = () => {
  const { content, shopCart } = useSelector((state: ApplicationState) => state)
  
  const [state, hookState] = useState({
    isOpen: false
  })

  const toggle = () => {
    hookState({
      isOpen: !state.isOpen
    })
  }

  const titleFormatter = (title: string = ''): string => {
    if(title?.includes('{quantity}'))
      return title.replace('{quantity}', `${shopCart?.items ? shopCart.items.length : 0}`)

    return title
  }

  return <header>
    <Navbar className="navbar-expand-sm navbar-toggleable-sm fixed-top border-bottom box-shadow mb-3 bg-light">
      <NavbarBrand href="/">{content?.siteName}</ NavbarBrand>
      <NavbarToggler onClick={toggle} className="mr-2"/>
      <Collapse className="d-sm-inline-flex flex-sm-row-reverse" isOpen={state.isOpen} navbar>
        <ul className="navbar-nav flex-grow">
          {content?.topMenu ? content.topMenu.map((item: MenuItemModel, index: number) => {
            return <NavItem key={index}>
              <NavLink tag={Link} className="text-dark" to={item.target}><>
                {item.icon ? <><FeatherIcon icon={item.icon}/> </> : ''}{titleFormatter(item.title)}</>
              </NavLink>
            </NavItem>
          }) : ''}
        </ul>
      </Collapse>
    </Navbar>
  </header>
}

export {
  NavMenu
}
