'use client';

import Link from 'next/link';
import { signOut } from 'next-auth/react';
import { Avatar, DropdownMenu } from '@/components/ui';

interface UserMenuProps {
  userName: string | null | undefined;
  userEmail: string;
}

export function UserMenu({ userName, userEmail }: UserMenuProps) {
  return (
    <DropdownMenu
      panelClassName="absolute right-0 z-20 mt-2 w-48 rounded-lg border border-border bg-card py-1 shadow-lg"
      trigger={({ open, toggle }) => (
        <button
          onClick={toggle}
          className="flex h-9 items-center gap-2 rounded-lg border border-border bg-card pl-1.5 pr-3 transition-colors hover:bg-card-hover"
        >
          <Avatar email={userEmail} name={userName} size={24} />
          <span className="text-sm font-medium text-foreground">
            {userName || userEmail.split('@')[0]}
          </span>
          <svg
            className={`h-4 w-4 text-muted transition-transform ${open ? 'rotate-180' : ''}`}
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
          </svg>
        </button>
      )}
    >
      {({ close }) => (
        <>
          <div className="border-b border-border px-4 py-2">
            <p className="text-xs text-muted">Connecté en tant que</p>
            <p className="truncate text-sm font-medium text-foreground">{userEmail}</p>
          </div>
          <Link
            href="/profile"
            onClick={close}
            className="block w-full px-4 py-2 text-left text-sm text-foreground hover:bg-card-hover"
          >
            👤 Mon Profil
          </Link>
          <Link
            href="/users"
            onClick={close}
            className="block w-full px-4 py-2 text-left text-sm text-foreground hover:bg-card-hover"
          >
            👥 Utilisateurs
          </Link>
          <button
            onClick={() => signOut({ callbackUrl: '/' })}
            className="w-full px-4 py-2 text-left text-sm text-destructive hover:bg-card-hover"
          >
            Se déconnecter
          </button>
        </>
      )}
    </DropdownMenu>
  );
}
