"use client";

import { useEffect, useMemo, useState } from "react";

import LogoutButton from "@/components/LogoutButton";
import { api } from "@/lib/api";
import type { CurrentUser } from "@/types/rbac";

export default function Header() {
  const [currentUser, setCurrentUser] = useState<CurrentUser | null>(null);

  useEffect(() => {
    let active = true;

    api.get<CurrentUser>("/me")
      .then((response) => {
        if (active) {
          setCurrentUser(response.data);
        }
      })
      .catch(() => {
        if (active) {
          setCurrentUser(null);
        }
      });

    return () => {
      active = false;
    };
  }, []);

  const displayName = useMemo(() => {
    if (!currentUser) {
      return "Benutzer";
    }

    const fullName = `${currentUser.first_name} ${currentUser.last_name}`.trim();
    return fullName || currentUser.username || "Benutzer";
  }, [currentUser]);

  return (
    <header className="flex h-20 items-center justify-between border-b bg-white px-8">
      <h1 className="text-3xl font-bold">Dashboard</h1>

      <div className="flex items-center gap-4">
        <span className="font-semibold">{displayName}</span>
        <LogoutButton />
      </div>
    </header>
  );
}
