"use client";

import Link from "next/link";
import { UserCircle, HomeIcon, Settings, User, LogOut } from "lucide-react";
import { deleteCookie } from "cookies-next";
import { useRouter } from "next/navigation";
import { LOGIN_STATUS_COOKIE } from "@/lib/common";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { cn } from "@/lib/utils";

interface UserMenuButtonProps {
  className?: string;
  isOpen: boolean;
  onToggle: () => void;
}

const USER_MENU_ITEMS = [
  { href: "/dashboard", label: "Dashboard", icon: HomeIcon },
  { href: "/settings/account", label: "Account Settings", icon: Settings },
  { href: "/settings/profile", label: "My Profile", icon: User },
] as const;

/**
 * Account menu, rebuilt on the shadcn `DropdownMenu` primitive.
 *
 * The previous version was a hand-rolled absolutely-positioned panel: it had no
 * `role="menu"`, no arrow-key navigation, no Escape handling, no focus return,
 * and it could not flip or shift when it ran out of room near the viewport
 * edge. It also navigated with `<a href>`, forcing a full document reload on
 * every item. Radix supplies the menu semantics and collision handling; links
 * are now `next/link`.
 *
 * `isOpen`/`onToggle` are still honoured so the header's mutual-exclusion logic
 * between this and the settings menu keeps working unchanged.
 */
export function UserMenuButton({ className, isOpen, onToggle }: UserMenuButtonProps) {
  const router = useRouter();

  const handleLogout = async () => {
    try {
      await fetch("/api/logout", { method: "POST" });
      deleteCookie(LOGIN_STATUS_COOKIE, { path: "/" });
      localStorage.clear();
      sessionStorage.clear();
      router.replace("/login");
    } catch (err) {
      console.error("Logout error:", err);
    }
  };

  return (
    <DropdownMenu open={isOpen} onOpenChange={onToggle}>
      <DropdownMenuTrigger asChild>
        <Button
          variant="outline"
          size="icon"
          aria-label="Account menu"
          data-header-user
          className={cn("text-primary", className)}
        >
          <UserCircle className="size-5" aria-hidden />
        </Button>
      </DropdownMenuTrigger>

      <DropdownMenuContent align="end" className="w-56">
        <DropdownMenuLabel>My account</DropdownMenuLabel>
        <DropdownMenuSeparator />

        {USER_MENU_ITEMS.map(({ href, label, icon: Icon }) => (
          <DropdownMenuItem key={label} asChild>
            <Link href={href}>
              <Icon className="size-4 text-muted-foreground" aria-hidden />
              {label}
            </Link>
          </DropdownMenuItem>
        ))}

        <DropdownMenuSeparator />
        <DropdownMenuItem variant="destructive" onSelect={handleLogout}>
          <LogOut className="size-4" aria-hidden />
          Log out
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
