import { Link, useNavigate } from "react-router";
import { authClient } from "~/lib/auth-client";
import { Popover, PopoverContent, PopoverTrigger } from "~/components/ui/popover";
import { Button } from "~/components/ui/button";
import { UserAvatar } from "~/components/ui/UserAvatar";
import type { RawFlagConfig } from "~/lib/flag-types";

interface UserMenuProps {
  userId: string;
  name: string | null;
  email: string;
  customAvatarUrl?: string | null;
  flagConfig?: RawFlagConfig | null;
  avatarType?: string | null;
}

export function UserMenu({
  userId,
  name,
  email,
  customAvatarUrl,
  flagConfig,
  avatarType,
}: UserMenuProps) {
  const navigate = useNavigate();

  async function handleSignOut() {
    await authClient.signOut();
    navigate("/");
  }

  return (
    <Popover>
      <PopoverTrigger asChild>
        <Button variant="ghost" className="relative h-9 w-9 p-0 rounded-none">
          <UserAvatar
            userId={userId}
            name={name}
            email={email}
            customAvatarUrl={customAvatarUrl}
            flagConfig={flagConfig}
            avatarType={avatarType}
          />
        </Button>
      </PopoverTrigger>
      <PopoverContent align="end" className="w-48 p-1">
        <div className="px-2 py-1.5 text-sm">
          <p className="font-medium truncate">{name ?? email}</p>
          <p className="text-muted-foreground truncate text-xs">{email}</p>
        </div>
        <div className="border-t border-border my-1" />
        <Link
          to="/settings"
          className="flex w-full items-center rounded-sm px-2 py-1.5 text-sm hover:bg-accent transition-colors"
        >
          Settings
        </Link>
        <div className="border-t border-border my-1" />
        <button
          onClick={handleSignOut}
          className="flex w-full items-center rounded-sm px-2 py-1.5 text-sm text-destructive hover:bg-accent transition-colors"
        >
          Sign Out
        </button>
      </PopoverContent>
    </Popover>
  );
}
