import { A } from "@solidjs/router";
import { JSXElement, Show, useContext } from "solid-js";

import { LoginContext, ModalContext } from "./GlobalState";
import { Flake, Home, Plus, UserCircle } from "./Icons";

// Represents a single list item in the menu bar
function MenuItem(props: { href: string; children: JSXElement }): JSXElement {
  return (
    <li>
      <A class="justify-center" href={props.href} end>
        {props.children}
      </A>
    </li>
  );
}

// Represents the menu bar at the top of the page
function Menu(): JSXElement {
  const login_ctx = useContext(LoginContext)!;
  return (
    <Show when={login_ctx.loggedIn()}>
      <ul class="menu space-y-2 rounded-box md:menu-horizontal md:space-x-2 md:space-y-0">
        <MenuItem href="/">
          <Home />
        </MenuItem>
        <MenuItem href="/new">
          <Plus />
        </MenuItem>
      </ul>
    </Show>
  );
}

export function Navbar(): JSXElement {
  const modal_ctx = useContext(ModalContext)!;
  const login_ctx = useContext(LoginContext)!;

  const clickHandler = (): void => {
    if (login_ctx.loggedIn()) login_ctx.logOut();
    else modal_ctx.setLoginModalOpen(true);
  };

  return (
    <div class="max-w navbar max-w-3xl rounded-box text-neutral-content md:my-4">
      <div class="flex-1">
        <A href={"/"} class="btn btn-ghost text-xl normal-case">
          <Flake />
          FrostByte
        </A>
      </div>
      <div class="flex">
        <Menu />
      </div>
      <div class="flex flex-1 justify-end">
        <A
          href="#"
          class="btn btn-ghost text-sm capitalize"
          onClick={clickHandler}
        >
          {
            <Show when={login_ctx.loggedIn()} fallback="Login">
              {login_ctx.username()}
            </Show>
          }
          <UserCircle />
        </A>
      </div>
    </div>
  );
}
