import * as Popover from "@radix-ui/react-popover";
import { useNavigate } from "@tanstack/react-router";
import { useMutation } from "@tanstack/react-query";
import { ChevronDown, LogOut, Settings as SettingsIcon } from "lucide-react";
import { toast } from "sonner";

import { api } from "@/lib/api";
import { authStore, useAuth } from "@/lib/auth";
import { cn } from "@/lib/utils";

/**
 * UserMenu — avatar initiales + popover avec logout.
 * Radix Popover pour l'a11y (focus management, échap, click-outside).
 */
export function UserMenu() {
  const { user } = useAuth();
  const navigate = useNavigate();

  const logoutMutation = useMutation({
    mutationFn: async () => api.post<void>("/api/v1/account/logout"),
    onSettled: () => {
      // Quoi qu'il arrive (succès ou échec réseau), on clear la session locale.
      authStore.clear();
      toast.success("À très vite.");
      void navigate({ to: "/login" });
    },
  });

  const initials = user?.fullName
    ?.split(" ")
    .filter(Boolean)
    .slice(0, 2)
    .map((part) => part[0]?.toUpperCase() ?? "")
    .join("") ?? "?";

  const firstName = user?.fullName?.split(" ")[0] ?? "Utilisateur";

  return (
    <Popover.Root>
      <Popover.Trigger
        className={cn(
          "inline-flex items-center gap-2 rounded-full border border-line bg-white",
          "py-1 pl-1 pr-2.5 transition-colors hover:border-ink-3",
          "focus-visible:outline-none focus-visible:ring-4 focus-visible:ring-rubis-glow",
        )}
        aria-label="Ouvrir le menu utilisateur"
      >
        <span
          className={cn(
            "flex size-7 items-center justify-center rounded-full bg-rubis text-white",
            "font-display text-[12.5px] font-bold leading-none",
          )}
          aria-hidden="true"
        >
          {initials}
        </span>
        <span className="hidden sm:inline text-[13px] font-medium text-ink">{firstName}</span>
        <ChevronDown size={14} className="text-ink-3" aria-hidden="true" />
      </Popover.Trigger>

      <Popover.Portal>
        <Popover.Content
          align="end"
          sideOffset={8}
          className={cn(
            "z-50 w-[220px] rounded-card border border-line bg-white p-2 shadow-card",
            "data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
          )}
        >
          <div className="px-3 py-2">
            <p className="text-[13px] font-semibold text-ink truncate">{user?.fullName}</p>
            <p className="text-[12px] text-ink-3 truncate">{user?.email}</p>
          </div>
          <div className="my-1 h-px bg-line" />
          <button
            type="button"
            onClick={() => navigate({ to: "/parametres" })}
            className="flex w-full items-center gap-2.5 rounded-default px-3 py-2 text-[13.5px] text-ink hover:bg-cream transition-colors"
          >
            <SettingsIcon size={15} className="text-ink-3" aria-hidden="true" />
            Paramètres
          </button>
          <button
            type="button"
            disabled={logoutMutation.isPending}
            onClick={() => logoutMutation.mutate()}
            className="flex w-full items-center gap-2.5 rounded-default px-3 py-2 text-[13.5px] text-ink hover:bg-cream transition-colors disabled:opacity-50"
          >
            <LogOut size={15} className="text-ink-3" aria-hidden="true" />
            Se déconnecter
          </button>
        </Popover.Content>
      </Popover.Portal>
    </Popover.Root>
  );
}
