"use client";
import React from "react";
import { Button } from "./ui/button";
import Link from "next/link";
import UserPopover from "@/app/_components/profile-popover";
import { appConfig } from "@/config/app.config";

import { Icons } from "./icons";
import { appRoutes } from "@/config/app.routes";
import { useSessionPlayerStore } from "@/lib/store/current-player-store";
import { useLobbyStore } from "@/lib/store/lobby-store";
import { usePathname } from "next/navigation";
import { cn } from "@/lib/utils";

function Navbar() {
  const sessionPlayer = useSessionPlayerStore((state) => state.sessionPlayer);
  const currentLobby = useLobbyStore((state) => state.lobby);

  const pathname = usePathname();

  return (
    <nav className="flex w-full items-center justify-center p-4">
      <div className="container-bg flex h-10 w-full max-w-sm items-center justify-between gap-2 overflow-hidden rounded-full border-2">
        <menu className="flex items-center">
          {appConfig.navigation.map((navLink, idx) => (
            <li key={idx}>
              <NavLink {...navLink} active={pathname === navLink.path} />
            </li>
          ))}
        </menu>

        <div
          className={cn(
            "bg-border/10 border-border/20 hover:bg-background/20 flex items-center rounded-full border-l-2",
            pathname === appRoutes.currentlobby && "bg-background/20",
          )}
        >
          {currentLobby ? (
            <Link href={appRoutes.currentlobby}>
              <div className="border-border/20 flex h-10 items-center justify-center gap-2 pr-2 pl-4 font-semibold">
                <Icons.logo className="size-4" />
                <span>Lobby</span>
              </div>
            </Link>
          ) : null}
          {sessionPlayer ? (
            <UserPopover player={sessionPlayer} />
          ) : (
            <Button asChild className="bg-primary font-black">
              <Link href="/api/auth/signin">Sign In</Link>
            </Button>
          )}
        </div>
      </div>
    </nav>
  );
}

const NavLink = ({
  label,
  path,
  active,
  className,
}: NavLink & { className?: string; active?: boolean }) => {
  return (
    <Button
      asChild
      variant={"ghost"}
      className={cn(
        "group hover:bg-background/20 h-10 rounded-none font-bold text-white/50 hover:text-white/50",
        active && "bg-background/20 text-white hover:text-white",
        className,
      )}
    >
      <Link href={path}>
        <span
          className={"transition-transform duration-150 group-hover:scale-105"}
        >
          {label}
        </span>
      </Link>
    </Button>
  );
};

export default Navbar;
