"use client";

import {
  ChevronsUpDownIcon,
  ExternalLinkIcon,
  LogOutIcon,
  UserRoundCogIcon,
} from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useTransition } from "react";

import { LogoMark } from "@/components/admin/logo";
import { UserAvatar } from "@/components/admin/user-avatar";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarGroup,
  SidebarGroupContent,
  SidebarHeader,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarRail,
  useSidebar,
} from "@/components/ui/sidebar";
import { adminNav } from "@/config/admin-nav";
import { logout } from "@/features/auth/actions";
import type { CurrentAdmin } from "@/lib/auth/session";

export function AppSidebar({
  admin,
  blogUrl,
}: {
  admin: CurrentAdmin;
  /** The public blog, when SITE_URL is configured. */
  blogUrl: string | null;
}) {
  const pathname = usePathname();
  const { isMobile, setOpenMobile } = useSidebar();
  const [signingOut, startSignOut] = useTransition();

  const isActive = (href: string, exact?: boolean) =>
    exact ? pathname === href : pathname === href || pathname.startsWith(`${href}/`);

  return (
    <Sidebar collapsible="icon">
      <SidebarHeader className="h-14 justify-center border-b border-sidebar-border px-3">
        <Link
          href="/admin"
          className="flex items-center gap-2.5 rounded-lg outline-none focus-visible:ring-2 focus-visible:ring-sidebar-ring"
        >
          <LogoMark />
          <span className="grid leading-tight group-data-[collapsible=icon]:hidden">
            <span className="text-sm font-semibold text-foreground">
              Wi-Fi Calling
            </span>
            <span className="text-xs text-muted-foreground">Blog CMS</span>
          </span>
        </Link>
      </SidebarHeader>

      <SidebarContent className="px-1 py-2">
        <SidebarGroup>
          <SidebarGroupContent>
            <SidebarMenu className="gap-0.5">
              {adminNav.map((item) => {
                const active = isActive(item.href, item.exact);
                return (
                  <SidebarMenuItem key={item.href}>
                    <SidebarMenuButton
                      asChild
                      isActive={active}
                      tooltip={item.title}
                      className="h-9 data-[active=true]:bg-accent data-[active=true]:text-accent-foreground [&_svg]:text-muted-foreground data-[active=true]:[&_svg]:text-primary"
                    >
                      <Link
                        href={item.href}
                        aria-current={active ? "page" : undefined}
                        onClick={() => isMobile && setOpenMobile(false)}
                      >
                        <item.icon />
                        <span>{item.title}</span>
                      </Link>
                    </SidebarMenuButton>
                  </SidebarMenuItem>
                );
              })}
            </SidebarMenu>
          </SidebarGroupContent>
        </SidebarGroup>
      </SidebarContent>

      <SidebarFooter className="border-t border-sidebar-border p-2">
        <SidebarMenu>
          <SidebarMenuItem>
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <SidebarMenuButton
                  size="lg"
                  className="data-[state=open]:bg-sidebar-accent"
                >
                  <UserAvatar
                    name={admin.name}
                    src={admin.avatarUrl}
                    className="size-8"
                  />
                  <span className="grid flex-1 text-left leading-tight">
                    <span className="truncate text-sm font-medium text-foreground">
                      {admin.name}
                    </span>
                    <span className="truncate text-xs text-muted-foreground">
                      {admin.email}
                    </span>
                  </span>
                  <ChevronsUpDownIcon className="ml-auto" />
                </SidebarMenuButton>
              </DropdownMenuTrigger>
              <DropdownMenuContent
                side={isMobile ? "top" : "right"}
                align="end"
                sideOffset={8}
                className="w-60"
              >
                <DropdownMenuLabel className="font-normal">
                  <span className="block text-sm font-medium text-foreground">
                    {admin.name}
                  </span>
                  <span className="block text-xs text-muted-foreground">
                    {admin.role === "ADMIN" ? "Administrator" : "Editor"}
                  </span>
                </DropdownMenuLabel>
                <DropdownMenuSeparator />
                <DropdownMenuItem asChild>
                  <Link href="/admin/settings">
                    <UserRoundCogIcon />
                    Account settings
                  </Link>
                </DropdownMenuItem>
                {blogUrl && (
                  <DropdownMenuItem asChild>
                    <a href={blogUrl} target="_blank" rel="noreferrer">
                      <ExternalLinkIcon />
                      View blog
                    </a>
                  </DropdownMenuItem>
                )}
                <DropdownMenuSeparator />
                <DropdownMenuItem
                  variant="destructive"
                  disabled={signingOut}
                  onSelect={(event) => {
                    event.preventDefault();
                    startSignOut(() => logout());
                  }}
                >
                  <LogOutIcon />
                  {signingOut ? "Signing out…" : "Log out"}
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </SidebarMenuItem>
        </SidebarMenu>
      </SidebarFooter>
      <SidebarRail />
    </Sidebar>
  );
}
