"use client";

import { ChevronLeft, ChevronRight, LogOut, NotebookPen } from "lucide-react";

import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { useSideNav } from "@/components/nav/side-nav-provider";
import { SideNavItem } from "@/components/nav/side-nav-item";
import { NAV_ITEMS, ADMIN_NAV_ITEM } from "@/components/nav/nav-items";
import { ThemeToggle } from "@/components/theme/theme-toggle";
import { logout } from "@/lib/actions/auth";
import { Role } from "@/lib/generated/prisma/enums";

export function SideNav({ userEmail, role }: { userEmail: string; role: Role }) {
  const { collapsed, toggle } = useSideNav();
  const items = role === Role.ADMIN ? [...NAV_ITEMS, ADMIN_NAV_ITEM] : NAV_ITEMS;

  return (
    <aside
      className={cn(
        "flex h-screen flex-col border-r bg-sidebar text-sidebar-foreground transition-[width] duration-200",
        collapsed ? "w-16" : "w-56"
      )}
    >
      <div className={cn("flex items-center gap-2 p-3", collapsed && "justify-center")}>
        <NotebookPen className="size-6 shrink-0 text-primary" />
        {!collapsed && <span className="truncate text-lg font-semibold">Organize</span>}
      </div>

      <Separator />

      <nav className="flex flex-1 flex-col gap-1 p-2">
        {items.map((item) => (
          <SideNavItem key={item.href} item={item} collapsed={collapsed} />
        ))}
      </nav>

      <Separator />

      <div className="flex flex-col gap-1 p-2">
        <ThemeToggle collapsed={collapsed} />

        {collapsed ? (
          <form action={logout}>
            <Tooltip>
              <TooltipTrigger
                render={
                  <Button variant="ghost" size="icon" type="submit" className="w-full">
                    <LogOut className="size-4" />
                  </Button>
                }
              />
              <TooltipContent side="right">Log out ({userEmail})</TooltipContent>
            </Tooltip>
          </form>
        ) : (
          <form action={logout}>
            <Button variant="ghost" type="submit" className="w-full justify-start gap-2">
              <LogOut className="size-4" />
              <span className="truncate">Log out</span>
            </Button>
          </form>
        )}

        {!collapsed && (
          <p className="truncate px-3 text-xs text-muted-foreground">{userEmail}</p>
        )}
      </div>

      <Separator />

      <div className={cn("flex p-2", collapsed ? "justify-center" : "justify-end")}>
        <Button variant="ghost" size="icon" onClick={toggle} aria-label="Toggle sidebar">
          {collapsed ? <ChevronRight className="size-4" /> : <ChevronLeft className="size-4" />}
        </Button>
      </div>
    </aside>
  );
}
