import { useState } from "react";
import { useLocation, useNavigate } from "react-router";
import client from "~/api/client";
import { useUserStore } from "~/hooks/user";

export default function NavBar() {
  const location = useLocation().pathname;
  const user = useUserStore((state) => state.user);
  const setUser = useUserStore((state) => state.setUser);
  const [popupOpen, setPopupOpen] = useState(false);
  const navigate = useNavigate();

  function handleProfileClick() {
    if (user) {
      setPopupOpen(!popupOpen);
    } else {
      navigate("/login");
    }
  }

  async function handleLogout() {
    const [_, status] = await client.POST("/logout", {
      token: user ? user.token : "",
    });
    setUser(null);
  }

  return (
    <div className="flex justify-between p-2">
      <div className="flex space-x-4">
        <a
          onClick={() => navigate("/")}
          className={
            "border-2 white rounded-md px-2 py-1" +
            (location === "/" ? " bg-gray-500" : "")
          }
        >
          Home
        </a>
      </div>
      <button
        onClick={handleProfileClick}
        className="border-2 white rounded-md px-2 py-1"
      >
        {user ? user.username : "Login"}
        {popupOpen ? (
          <>
            <div
              className="w-screen h-screen absolute top-0 left-0 z-[99]"
              onClick={() => {
                setPopupOpen(!popupOpen);
              }}
            ></div>
            <div className="absolute mt-3 -ml-14 bg-red-600 flex flex-col rounded-md justify-center items-center z-[100] space-y-0.5 w-25 py-1">
              <a className="px-2 py-1 hover:bg-blue-400 w-[90%] rounded-md">
                Profile
              </a>
              <a className="px-2 py-1 hover:bg-blue-400 w-[90%] rounded-md">
                Settings
              </a>
              <div className="bg-amber-300 w-[90%] h-[2px] rounded-md"></div>
              <a
                onClick={handleLogout}
                className="px-2 py-1 hover:bg-blue-400 w-[90%] rounded-md"
              >
                Logout
              </a>
            </div>
          </>
        ) : (
          <></>
        )}
      </button>
    </div>
  );
}
