import type {FC, MouseEvent} from 'react';
import React, {useContext} from 'react';
import {context, Link, NavLink} from 'dumi/theme';
import LocaleSelect from './LocaleSelect';
import './Navbar.less';

interface INavbarProps {
  location: any;
  navPrefix?: React.ReactNode;
  darkPrefix?: React.ReactNode;
  onMobileMenuClick: (ev: MouseEvent<HTMLButtonElement>) => void;
}

const Navbar: FC<INavbarProps> = ({onMobileMenuClick, navPrefix, location, darkPrefix}) => {
  const {
    base,
    config: {mode, title, logo},
    nav: navItems
  } = useContext(context);

  return (
    <div
      className={`__dumi-default-navbar ${
        location.pathname === '/' ? '__dumi-default-active' : ''
      }`}
      data-mode={mode}
    >
      {/* menu toggle button (only for mobile) */}
      <button className="__dumi-default-navbar-toggle" onClick={onMobileMenuClick} />
      {/* logo & title */}
      <Link
        className="__dumi-default-navbar-logo"
        to={base}
        data-plaintext={logo === false || undefined}
      >
        <div className="__dumi-default-navbar-logo-inner">
          <div className="__dumi-default-navbar-logo-icon">
            <img src={typeof logo === 'string' ? logo : ''} alt="" />
          </div>
          <div onClick={event => event.preventDefault()}>{navPrefix}</div>
        </div>
      </Link>
      <nav>
        {/* nav */}
        {navItems.map(nav => {
          const child = Boolean(nav.children?.length) && (
            <ul>
              {nav.children.map(item => (
                <li key={item.path}>
                  {item.path ? <NavLink to={item.path}>{item.title}</NavLink> : null}
                </li>
              ))}
            </ul>
          );

          return (
            <span key={nav.title || nav.path}>
              {nav.path ? (
                <NavLink to={nav.path} key={nav.path}>
                  {nav.title}
                </NavLink>
              ) : (
                nav.title
              )}
              {child}
            </span>
          );
        })}
        <LocaleSelect location={location} />
        {darkPrefix}
      </nav>
    </div>
  );
};

export default Navbar;
