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";

interface UserMenuProps {
  name: string | null;
  email: string;
  imageUrl: string | null;
}

export function UserMenu({ name, email, imageUrl }: UserMenuProps) {
  const navigate = useNavigate();

  const initials = name
    ? name.split(" ").map((n) => n[0]).join("").toUpperCase().slice(0, 2)
    : email.slice(0, 2).toUpperCase();

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

  return (
    <Popover>
      <PopoverTrigger asChild>
        <Button variant="ghost" className="relative h-9 w-9 rounded-full p-0 overflow-hidden">
          {imageUrl ? (
            <img src={imageUrl} alt={name ?? email} className="h-9 w-9 rounded-full object-cover" />
          ) : (
            <span className="flex h-9 w-9 items-center justify-center rounded-full bg-muted text-sm font-medium">
              {initials}
            </span>
          )}
        </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="/user-profile"
          className="flex w-full items-center rounded-sm px-2 py-1.5 text-sm hover:bg-accent transition-colors"
        >
          Profile
        </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>
  );
}
