"use client";

import { useAuth } from "@/composables/useAuth";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@radix-ui/react-dropdown-menu";
import { LogOut } from "lucide-react";

function getInitials(name: string) {
  return name
    .split(" ")
    .map((n) => n[0])
    .join("")
    .toUpperCase()
    .slice(0, 2)
}

export function Header() {
  const { user, logout, isLoadingUser } = useAuth();

  const initials = user ? getInitials(user.full_name || user.username) : "?";
  const displayName = user?.full_name || user?.username || "Loading...";
  const displayRole = user?.role || "";

  const handleLogout = async () => {
    try {
      await logout();
    } catch (error) {
      console.error("Logout failed:", error);
    }
  };

  return (
    <header className="h-16 bg-white border-b border-gray-200 px-8 flex items-center justify-between">
      <div></div>
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <div className="flex items-center gap-2 mt-0 cursor-pointer">
            <div className="w-8 h-8 bg-gradient-to-br from-pink-300 to-orange-300 rounded-full flex items-center justify-center text-white text-sm font-semibold">
              {initials}
            </div>
            <div className="flex items-start flex-col">
              <span className="text-sm">{displayName}</span>
              <span className="text-xs text-gray-500">{displayRole}</span>
            </div>
            </div>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end" className="bg-white border border-gray-200 rounded-md shadow-lg">
          <DropdownMenuItem
            disabled={isLoadingUser}
            onClick={handleLogout}
            className="px-4 py-2 text-sm text-red-600 hover:bg-red-50 flex items-center gap-2 cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <LogOut className="w-4 h-4" />
            Logout
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    </header>
  );
}