import { Link } from 'react-router';
import { toast } from 'sonner';
import { FolderOpen, Star, StarOff } from 'lucide-react';
import {
  DropdownMenu,
  DropdownMenuTrigger,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
} from '@/components/ui/dropdown-menu';
import { useSoulseekFavorites } from './useSoulseekFavorites';
import { soulseekUserPath } from './shared';

// The peer dropdown, shared by search results and downloads: click a username anywhere in the workspace
// and act on that peer. Opening a peer is a real link to /soulseek/users?user=<name> — the Users section
// still owns the lookup and the cached share tree, it just reads who from the URL. Favouriting is a
// mutation, so it stays a menu item that acts rather than navigates.

type UserMenuProps = { username: string };

export const UserMenu = ({ username }: UserMenuProps) => {
  const { isFavorite, toggle } = useSoulseekFavorites();
  const favorited = isFavorite(username);

  const toggleFavorite = () => {
    toggle(username);
    toast.success(favorited ? `Removed ${username} from favorites` : `Added ${username} to favorites`);
  };

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <button
          type="button"
          title={`Actions for ${username}`}
          className="min-w-0 max-w-full truncate rounded text-sm font-medium text-zinc-100 underline decoration-dotted decoration-zinc-600 underline-offset-4 outline-none transition hover:decoration-zinc-300 focus-visible:ring-2 focus-visible:ring-primary/40"
        >
          {username}
          {favorited && <Star className="ml-1.5 inline h-3 w-3 fill-amber-400 align-baseline text-amber-400" />}
        </button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="start" className="w-56">
        <DropdownMenuLabel className="truncate">{username}</DropdownMenuLabel>
        <DropdownMenuSeparator />
        <DropdownMenuItem asChild>
          <Link to={soulseekUserPath(username)}>
            <FolderOpen className="mr-2 h-4 w-4" />
            View profile &amp; shares
          </Link>
        </DropdownMenuItem>
        <DropdownMenuItem onSelect={toggleFavorite}>
          {favorited ? <StarOff className="mr-2 h-4 w-4" /> : <Star className="mr-2 h-4 w-4" />}
          {favorited ? 'Remove from favorites' : 'Add user to favorites'}
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  );
};
