import { redirect } from "next/navigation";
import Link from "next/link";
import { getCurrentSession } from "@/lib/auth";
import { PermissionKey } from "@prisma/client";
import LogoutButton from "@/components/LogoutButton";

const NAV: { href: string; label: string; permission?: PermissionKey }[] = [
  { href: "/dashboard", label: "Dashboard" },
  { href: "/employees", label: "Employees", permission: PermissionKey.VIEW_EMPLOYEES },
  { href: "/map", label: "Live Map", permission: PermissionKey.VIEW_LIVE_LOCATION },
  { href: "/geofences", label: "Geofences", permission: PermissionKey.MANAGE_GEOFENCES },
  { href: "/vehicles", label: "Vehicles", permission: PermissionKey.MANAGE_VEHICLES },
  { href: "/devices", label: "Devices", permission: PermissionKey.VIEW_DEVICES },
  { href: "/attendance", label: "Attendance", permission: PermissionKey.VIEW_EMPLOYEES },
  { href: "/emergency", label: "Emergency", permission: PermissionKey.VIEW_EMERGENCY },
  { href: "/audit", label: "Audit Logs", permission: PermissionKey.VIEW_AUDIT_LOGS },
  { href: "/settings", label: "Settings", permission: PermissionKey.MANAGE_SETTINGS },
];

export default async function HrLayout({ children }: { children: React.ReactNode }) {
  const session = await getCurrentSession();
  if (!session) redirect("/login");
  if (!session.user.isAdmin) redirect("/portal");

  const visibleNav = NAV.filter((n) => !n.permission || session.permissions.includes(n.permission));

  return (
    <div className="min-h-screen bg-slate-950 text-slate-100 flex">
      <aside className="w-60 border-r border-slate-800 bg-slate-900 flex flex-col">
        <div className="px-5 py-5 border-b border-slate-800">
          <div className="font-semibold">Kothay Jaba</div>
          <div className="text-xs text-slate-500">HR / Security Admin</div>
        </div>
        <nav className="flex-1 px-2 py-3 space-y-0.5">
          {visibleNav.map((n) => (
            <Link
              key={n.href}
              href={n.href}
              className="block rounded-md px-3 py-2 text-sm text-slate-300 hover:bg-slate-800 hover:text-white transition"
            >
              {n.label}
            </Link>
          ))}
        </nav>
        <div className="px-4 py-4 border-t border-slate-800 text-xs text-slate-400">
          <div className="truncate">{session.user.name}</div>
          <div className="truncate text-slate-500">{session.roleName}</div>
          <LogoutButton />
        </div>
      </aside>
      <main className="flex-1 overflow-y-auto">{children}</main>
    </div>
  );
}
