"use client";

import { useState, useRef, useEffect } from "react";
import { useRouter, usePathname } from "next/navigation";
import { Bell, LogOut, ChevronDown } from "lucide-react";
import { useAuth } from "@/context/AuthContext";

const ROLE_LABELS: Record<string, string> = {
  ADMIN: "HR ADMIN",
  HR_MANAGER: "HR Manager",
  COMPLIANCE_OFFICER: "Compliance Officer",
  SUPERVISOR: "Supervisor",
  VIEWER: "Viewer",
  EMPLOYEE: "Employee",
};

const PAGE_TITLES: Record<string, string> = {
  "/dashboard":                  "Dashboard",
  "/dashboard/employees":        "Employees",
  "/dashboard/attendance":       "Attendance",
  "/dashboard/payroll":          "Payroll",
  "/dashboard/loans":            "Loans & Advances",
  "/dashboard/leave":            "Leave Management",
  "/dashboard/compliance":       "Compliance",
  "/dashboard/social-security":  "Social Security",
  "/dashboard/training":         "Training",
  "/dashboard/contracts":        "Contracts",
  "/dashboard/reports":          "Reports",
  "/dashboard/settings":         "Settings",
};

export function Header() {
  const router = useRouter();
  const pathname = usePathname();
  const { user, logout } = useAuth();
  const [menuOpen, setMenuOpen] = useState(false);
  const menuRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(e.target as Node)) {
        setMenuOpen(false);
      }
    };
    if (menuOpen) document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [menuOpen]);

  const handleLogout = () => {
    logout();
    setMenuOpen(false);
    router.replace("/login");
  };

  const initials = user?.name
    ? user.name.split(" ").map((w) => w[0]).join("").toUpperCase().slice(0, 2)
    : "??";

  const displayName = user?.name || user?.email || "User";
  const roleLabel = user?.role ? (ROLE_LABELS[user.role] || user.role) : "";

  const pageTitle = Object.entries(PAGE_TITLES).find(([key]) =>
    pathname === key || pathname?.startsWith(key + "/")
  )?.[1] ?? "Dashboard";

  return (
    <header className="sticky top-0 z-40 bg-white border-b border-gray-100">
      <div className="flex h-14 items-center justify-between px-6 lg:px-8">

        {/* Page title */}
        <div className="flex items-center gap-2">
          <h1 className="text-sm font-semibold text-gray-900">{pageTitle}</h1>
        </div>

        {/* Right actions */}
        <div className="flex items-center gap-3">

          {/* Notification bell */}
          <button
            type="button"
            className="relative flex h-8 w-8 items-center justify-center rounded-md text-gray-400 hover:bg-gray-50 hover:text-gray-600 transition-colors"
          >
            <Bell className="h-4 w-4" />
            <span className="absolute top-1.5 right-1.5 h-1.5 w-1.5 rounded-full bg-red-500" />
          </button>

          <div className="h-5 w-px bg-gray-200" />

          {/* User menu */}
          <div className="relative" ref={menuRef}>
            <button
              type="button"
              onClick={() => setMenuOpen((o) => !o)}
              className="flex items-center gap-2.5 rounded-md px-2 py-1.5 hover:bg-gray-50 transition-colors"
            >
              <div className="h-7 w-7 rounded-full bg-[#131312] flex items-center justify-center">
                <span className="text-white font-semibold text-xs">{initials}</span>
              </div>
              <div className="hidden lg:block text-left">
                <p className="text-xs font-semibold text-gray-900 leading-none">{displayName}</p>
                {roleLabel && <p className="text-[10px] text-gray-400 mt-0.5">{roleLabel}</p>}
              </div>
              <ChevronDown className="h-3 w-3 text-gray-400 hidden lg:block" />
            </button>

            {menuOpen && (
              <div className="absolute right-0 mt-1.5 w-44 rounded-lg bg-white shadow-lg ring-1 ring-gray-200 py-1 z-50">
                <div className="px-3 py-2 border-b border-gray-100">
                  <p className="text-xs font-semibold text-gray-900 truncate">{displayName}</p>
                  {roleLabel && <p className="text-[10px] text-gray-400">{roleLabel}</p>}
                </div>
                <button
                  type="button"
                  onClick={handleLogout}
                  className="flex w-full items-center gap-2 px-3 py-2 text-sm text-gray-600 hover:bg-gray-50 hover:text-gray-900 transition-colors"
                >
                  <LogOut className="h-3.5 w-3.5" />
                  Sign out
                </button>
              </div>
            )}
          </div>
        </div>
      </div>
    </header>
  );
}
