import { useContext } from "solid-js";
import { A } from "@solidjs/router";
import { LoginContext } from "./Root";
import { ModalContext } from "./Root";
import { LoginForm } from "./Login";

function Menu() {
  let login_ctx = useContext(LoginContext);
  return (
    <ul class="menu menu-horizontal bg-base-200 rounded-box space-x-2">
      <li>
        <A href="/" end>
          Home
        </A>
      </li>
      {login_ctx?.token() != "" ? (
        <li>
          <A href="/new" end>
            New
          </A>
        </li>
      ) : (
        <></>
      )}
    </ul>
  );
}

export function Navbar() {
  let modal_ctx = useContext(ModalContext);
  let login_ctx = useContext(LoginContext);

  return (
    <div class="navbar bg-base-100 max-w-3xl max-w flex justify-around">
      <a class="btn btn-ghost normal-case text-xl">FrostByte</a>
      <Menu />
      <A
        href="#"
        class="btn btn-ghost normal-case text-sm"
        onClick={(b) => {
          b.preventDefault();
          if (login_ctx?.token() != "") {
            localStorage.setItem("token", "");
            localStorage.setItem("username", "");
            login_ctx?.setToken("");
            login_ctx?.setUsername("");
            return;
          }
          modal_ctx?.setLoginModalOpen(true);
        }}
      >
        {login_ctx?.token() != "" ? login_ctx?.username() : "Login"}
      </A>
    </div>
  );
}

// This is a modal
export function Login() {
  const modal_ctx = useContext(ModalContext);
  return (
    <dialog id="login_modal" class="modal" open={modal_ctx?.loginModalOpen()}>
      <div class="modal-box">
        <h3 class="font-bold text-lg">Hello!</h3>
        <p class="py-4">Login to your FrostByte account.</p>
        <LoginForm />
      </div>
      <form
        method="dialog"
        // This backdrop renders choppy on my machine. Likely because of the blur filter or misuse of css transisions
        class="modal-backdrop backdrop-brightness-50 backdrop-blur-sm backdrop-contrast-100 transition-all transition-300"
        onsubmit={(e) => {
          // This is just needed to set the state to false
          // The modal will close itself without this code, but without setting the state
          e.preventDefault();
          modal_ctx?.setLoginModalOpen(false);
        }}
      >
        <button>close</button>
      </form>
    </dialog>
  );
}
