"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useState } from "react";
import { signOut } from "next-auth/react";
import { cn } from "@/lib/utils";
import {
  LayoutDashboard,
  Users,
  Building2,
  GitBranch,
  CalendarOff,
  Clock,
  DollarSign,
  ScanLine,
  UserCog,
  ShieldCheck,
  LogOut,
  ChevronDown,
  LockIcon,
} from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";

type Permission = {
  module: string;
  actions: string[];
};

type User = {
  name?: string | null;
  email?: string | null;
  role: string;
  roles?: string[]; // ← added so sidebar knows the role list
};

type NavItem = {
  label: string;
  href: string;
  module: string | null;
  icon: React.ReactNode;
  onlyForRoles?: string[];
  hiddenForRoles?: string[];
};

type NavGroup = {
  label: string;
  items: NavItem[];
};

const navGroups: NavGroup[] = [
  {
    label: "Dashboard",
    items: [
      {
        label: "Dashboard",
        href: "/dashboard",
        module: null,
        icon: <LayoutDashboard className="h-4 w-4" />,
        hiddenForRoles: ["employee"], // employees get their own dashboard link below
      },
      {
        label: "Dashboard",
        href: "/dashboard/employee",
        module: null,
        icon: <LayoutDashboard className="h-4 w-4" />,
        onlyForRoles: ["employee"],
      },
    ],
  },
  {
    label: "Employee",
    items: [
      {
        label: "Employees",
        href: "/employees",
        module: "employees",
        icon: <Users className="h-4 w-4" />,
        hiddenForRoles: ["employee"],
      },
      {
        label: "Departments",
        href: "/departments",
        module: "departments",
        icon: <Building2 className="h-4 w-4" />,
        hiddenForRoles: ["employee"],
      },
      {
        label: "Company",
        href: "/branches",
        module: "branches",
        icon: <GitBranch className="h-4 w-4" />,
        hiddenForRoles: ["employee"],
      },
      // Admin leave management
      {
        label: "Leave",
        href: "/leave",
        module: "leave",
        icon: <CalendarOff className="h-4 w-4" />,
        hiddenForRoles: ["employee"],
      },
      // Employee self-service leave
      {
        label: "My Leave",
        href: "/leave/empolyee",
        module: null,
        icon: <CalendarOff className="h-4 w-4" />,
        onlyForRoles: ["employee"],
      },
      {
        label: "Shifts",
        href: "/shifts",
        module: "shifts",
        icon: <Clock className="h-4 w-4" />,
        hiddenForRoles: ["employee"],
      },
      {
        label: "Payroll",
        href: "/payroll",
        module: "payroll",
        icon: <DollarSign className="h-4 w-4" />,
        hiddenForRoles: ["employee"],
      },
      {
        label: "Attendance",
        href: "/attendance",
        module: "attendance",
        icon: <ScanLine className="h-4 w-4" />,
        hiddenForRoles: ["employee"],
      },
    ],
  },
  {
    label: "Settings",
    items: [
      {
        label: "Users",
        href: "/users",
        module: "users",
        icon: <UserCog className="h-4 w-4" />,
        hiddenForRoles: ["employee"],
      },
      {
        label: "Roles",
        href: "/roles",
        module: "roles",
        icon: <ShieldCheck className="h-4 w-4" />,
        hiddenForRoles: ["employee"],
      },
      {
        label: "Change Password",
        href: "/change-password",
        module: "settings",
        icon: <LockIcon className="h-4 w-4" />,
      },
    ],
  },
];

function hasPermission(item: NavItem, permissions: Permission[]) {
  if (item.module === null) return true;
  return permissions.some(
    (p) => p.module === item.module && p.actions.includes("view"),
  );
}

function matchesRole(item: NavItem, userRoles: string[]): boolean {
  const lower = userRoles.map((r) => r.toLowerCase());
  if (item.onlyForRoles && !item.onlyForRoles.some((r) => lower.includes(r)))
    return false;
  if (item.hiddenForRoles && item.hiddenForRoles.some((r) => lower.includes(r)))
    return false;
  return true;
}

// ─── Sidebar ──────────────────────────────────────────────────────────────────

export default function Sidebar({
  permissions,
  user,
}: {
  permissions: Permission[];
  user: User;
}) {
  const pathname = usePathname();
  const [logoutOpen, setLogoutOpen] = useState(false);
  const [loggingOut, setLoggingOut] = useState(false);

  const userRoles = Array.isArray(user.roles)
    ? user.roles
    : user.role
      ? [user.role]
      : [];

  const [expanded, setExpanded] = useState<Record<string, boolean>>(() => {
    const initial: Record<string, boolean> = {};
    navGroups.forEach((group) => {
      const hasActive = group.items.some(
        (item) =>
          pathname === item.href ||
          (item.href !== "/dashboard" &&
            item.href !== "/dashboard/employee" &&
            pathname.startsWith(item.href)),
      );
      if (hasActive) initial[group.label] = true;
    });
    return initial;
  });

  async function handleLogout() {
    setLoggingOut(true);
    // Use relative path to work correctly in both dev and production
    await signOut({ callbackUrl: "/login", redirect: true });
  }

  return (
    <>
      <aside className="fixed inset-y-0 left-0 z-50 hidden w-[260px] flex-col border-r bg-slate-950 text-slate-200 lg:flex">
        {/* ── Top: User card ── */}
        <div className="border-b border-slate-800 px-5 py-4">
          <div className="flex items-center gap-3 rounded-lg bg-slate-800/60 px-3 py-2.5">
            <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary text-xs font-bold uppercase text-primary-foreground">
              {user.name ? user.name.charAt(0) : "U"}
            </div>
            <div className="min-w-0">
              <p className="truncate text-sm font-medium leading-none text-slate-100">
                {user.name || "User"}
              </p>
              <p className="mt-0.5 truncate text-xs text-slate-400">
                {user.email || ""}
              </p>
            </div>
          </div>
        </div>

        {/* ── Navigation ── */}
        <nav className="flex-1 space-y-1 overflow-y-auto px-3 py-3">
          {navGroups.map((group) => {
            const visibleItems = group.items.filter(
              (item) =>
                hasPermission(item, permissions) &&
                matchesRole(item, userRoles),
            );
            if (visibleItems.length === 0) return null;

            if (group.label === "Dashboard") {
              return (
                <div key={group.label} className="space-y-0.5">
                  {visibleItems.map((item) => (
                    <NavLink key={item.href} item={item} pathname={pathname} />
                  ))}
                </div>
              );
            }

            if (group.label === "Employee" || group.label === "Settings") {
              return (
                <div key={group.label} className="space-y-0.5">
                  <p className="mb-1 px-3 text-[10px] font-semibold uppercase tracking-widest text-slate-500">
                    {group.label}
                  </p>
                  {visibleItems.map((item) => (
                    <NavLink key={item.href} item={item} pathname={pathname} />
                  ))}
                </div>
              );
            }

            const isExpanded = expanded[group.label] ?? false;
            const hasActiveChild = visibleItems.some(
              (item) =>
                pathname === item.href ||
                (item.href !== "/dashboard" && pathname.startsWith(item.href)),
            );

            return (
              <div key={group.label} className="space-y-0.5">
                <button
                  onClick={() =>
                    setExpanded((prev) => ({
                      ...prev,
                      [group.label]: !isExpanded,
                    }))
                  }
                  className={cn(
                    "flex h-10 w-full items-center justify-between rounded-md px-3 text-sm font-medium transition-colors",
                    hasActiveChild
                      ? "bg-primary/20 text-slate-100"
                      : "text-slate-300 hover:bg-slate-800/60 hover:text-slate-50",
                  )}
                >
                  <span>{group.label}</span>
                  <ChevronDown
                    className={cn(
                      "h-4 w-4 transition-transform text-slate-400",
                      isExpanded && "rotate-180",
                    )}
                  />
                </button>

                {isExpanded && (
                  <div className="space-y-0.5 pl-4">
                    {visibleItems.map((item) => (
                      <NavLink
                        key={item.href}
                        item={item}
                        pathname={pathname}
                      />
                    ))}
                  </div>
                )}
              </div>
            );
          })}
        </nav>

        <div className="border-t border-slate-800 px-3 py-3">
          <button
            onClick={() => setLogoutOpen(true)}
            className="flex h-10 w-full items-center gap-3 rounded-md px-3 text-sm font-medium text-slate-300 transition-colors hover:bg-red-500/15 hover:text-red-400"
          >
            <LogOut className="h-4 w-4" />
            Logout
          </button>
        </div>
      </aside>

      <Dialog open={logoutOpen} onOpenChange={setLogoutOpen}>
        <DialogContent className="sm:max-w-[360px]">
          <DialogHeader>
            <div className="mb-3 flex h-12 w-12 items-center justify-center rounded-full bg-red-100 text-red-600">
              <LogOut className="h-5 w-5" />
            </div>
            <DialogTitle>Sign out</DialogTitle>
            <DialogDescription>
              Are you sure you want to sign out? You'll need to log in again to
              access the system.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter className="mt-2 gap-2 sm:gap-2">
            <Button
              variant="outline"
              onClick={() => setLogoutOpen(false)}
              disabled={loggingOut}
            >
              Cancel
            </Button>
            <Button
              variant="destructive"
              onClick={handleLogout}
              disabled={loggingOut}
            >
              {loggingOut ? "Signing out…" : "Sign out"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}

// ─── NavLink ──────────────────────────────────────────────────────────────────

function NavLink({ item, pathname }: { item: NavItem; pathname: string }) {
  const isActive =
    pathname === item.href ||
    (item.href !== "/dashboard" &&
      item.href !== "/dashboard/employee" &&
      pathname.startsWith(item.href));

  return (
    <Link
      href={item.href}
      className={cn(
        "flex h-10 items-center gap-3 rounded-md px-3 text-sm font-medium transition-colors",
        isActive
          ? "bg-primary text-primary-foreground"
          : "text-slate-300 hover:bg-slate-800/60 hover:text-slate-50",
      )}
    >
      <span
        className={cn(isActive ? "text-primary-foreground" : "text-slate-400")}
      >
        {item.icon}
      </span>
      {item.label}
    </Link>
  );
}
