"use client";

import { LogOut, School } from "lucide-react";
import { useRouter } from "next/navigation";

import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { SidebarTrigger } from "@/components/ui/sidebar";
import { useAuth } from "@/contexts/auth-context";
import { useSchool } from "@/hooks/use-school";

export function SiteHeader() {
  const router = useRouter();
  const { user, logout } = useAuth();
  const { school } = useSchool();

  const handleLogout = async () => {
    try {
      logout();
      router.push("/auth/login");
    } catch (error) {
      console.error("Logout failed:", error);
    }
  };

  const userName = user?.name || user?.username || (user?.email ? user.email.split("@")[0] : "User");
  const schoolName = school?.namaSekolah || "SISADIK";

  return (
    <header className="flex h-12 shrink-0 items-center gap-2 border-b transition-[width,height] ease-linear group-has-data-[collapsible=icon]/sidebar-wrapper:h-12">
      <div className="flex w-full items-center justify-between gap-1 px-4 lg:gap-2 lg:px-6">
        <div className="flex items-center gap-1 lg:gap-2">
          <SidebarTrigger className="-ml-1" />
          <Separator orientation="vertical" className="mx-2 data-[orientation=vertical]:h-4" />
          <div className="flex items-center gap-2">
            <School className="text-primary h-4 w-4" />
            <h1 className="text-base font-medium">{schoolName}</h1>
          </div>
        </div>

        {user && (
          <div className="flex items-center gap-2">
            <span className="text-muted-foreground text-sm">Welcome, {userName}</span>
            <span className="text-muted-foreground bg-secondary rounded-md px-2 py-1 text-xs">{user.role}</span>
            <Button variant="ghost" size="sm" onClick={handleLogout}>
              <LogOut className="h-4 w-4" />
              <span className="ml-2 hidden sm:inline">Logout</span>
            </Button>
          </div>
        )}
      </div>
    </header>
  );
}
