"use client";

import { displayValue } from "@/lib/display-format";

import Link from "next/link";
import { SinghLogo } from "@/components/singh-logo";
import { useAccess } from "@/features/auth/hooks/use-access";
import { usePathname } from "next/navigation";
import { useState, useMemo } from "react";
import { useLogout } from "@/features/auth/hooks/use-logout";
import { useCartContext } from "@/features/cart/components/cart-context";
import {
  LayoutDashboard,
  Building2,
  Package,
  ShoppingCart,
  LogOut,
  Bell,
  Menu,
  X,
  Shield,
  UserCog,
  ChevronDown,
  ChevronRight,
  Settings,
  Users,
  Boxes,
  BarChart3,
} from "lucide-react";
import type { SidebarPermission } from "@/features/manage-users/dtos/manage-users.dto";

interface NavItem {
  name: string;
  href: SidebarPermission;
  icon: React.ComponentType<{ className?: string }>;
  group?: string;
}


const allNavigation: NavItem[] = [
  { name: "Dashboard", href: "/dashboard", icon: LayoutDashboard },
  { name: "Companies", href: "/companies", icon: Building2 },
  { name: "Configure Products", href: "/products", icon: Package },
  { name: "Stock Management", href: "/stock-management", icon: Boxes },
  { name: "Orders", href: "/orders", icon: ShoppingCart },
  { name: "New Order", href: "/orders/new", icon: Package },

  { name: "MIS Reporting", href: "/mis-reporting", icon: BarChart3 },
  { name: "Notifications", href: "/notifications", icon: Bell },
];

const permissionNavItems: NavItem[] = [
  { name: "Manage Roles", href: "/manage-roles", icon: Shield, group: "Permissions" },
  { name: "Manage Users", href: "/manage-users", icon: Users, group: "Permissions" },
];

// ============================================
// Get current user role from localStorage
// ============================================

function getUserInitials(name: string): string {
  return name
    .split(" ")
    .map((n) => n[0])
    .join("")
    .toUpperCase()
    .slice(0, 2);
}

// ============================================
// Admin Layout Component
// ============================================

interface AdminLayoutProps {
  children: React.ReactNode;
  companyUsersActive?: boolean;
  communitiesActive?: boolean;
}

export function AdminLayout({ children, companyUsersActive = false }: AdminLayoutProps) {
  const { can, canPage, userName, roleName } = useAccess();
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [permissionsOpen, setPermissionsOpen] = useState(false);
  const [companyOpen, setCompanyOpen] = useState<boolean | null>(null);
  const pathname = usePathname();
  const isCompanyActive = pathname.startsWith("/companies") || companyUsersActive;
  const companyExpanded = companyOpen ?? isCompanyActive;
  const { logout, loading: logoutLoading } = useLogout();
  const { itemCount: cartItemCount } = useCartContext();

  const allowedNavigation = allNavigation.filter((item) => canPage(item.href));
  const allowedPermissionItems = permissionNavItems.filter((item) => canPage(item.href) && (item.href !== "/manage-users" || can("users.view")));
  const hasPermissionItems = allowedPermissionItems.length > 0;

  // Check if any sub-item under Permissions is active
  const isPermissionsActive = useMemo(() => {
    return pathname === "/manage-roles" || (pathname === "/manage-users" && !companyUsersActive);
  }, [pathname, companyUsersActive]);

  return (
    <div className="flex h-screen bg-[#f0f2f5]">
      {/* Mobile sidebar overlay */}
      {sidebarOpen && (
        <div
          className="fixed inset-0 z-40 bg-black/60 backdrop-blur-sm lg:hidden"
          onClick={() => setSidebarOpen(false)}
        />
      )}

      {/* ============================================ */}
      {/* Sidebar — Dark Navy Gradient */}
      {/* ============================================ */}
      <aside
        className={`fixed inset-y-0 left-0 z-50 flex w-64 flex-col bg-gradient-to-b from-navy-950 via-navy-900 to-navy-800 shadow-2xl transition-transform duration-300 ease-in-out lg:static lg:translate-x-0 ${
          sidebarOpen ? "translate-x-0" : "-translate-x-full"
        }`}
      >
        {/* Logo */}
        <div className="flex h-16 items-center justify-between px-6 border-b border-white/10">
          <Link href="/dashboard" className="flex items-center gap-3">
            <SinghLogo className="w-28" />
          </Link>
          <button
            onClick={() => setSidebarOpen(false)}
            className="lg:hidden text-white/60 hover:text-white transition-colors"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        {/* Navigation */}
        <nav className="flex-1 space-y-1 px-3 py-5 overflow-y-auto">
          {/* Main nav items (filtered by role) */}
          {allowedNavigation.map((item) => {
            if (item.href === "/companies") {
              return (
                <div key={item.name}>
                  <button type="button" aria-expanded={companyExpanded} aria-controls="company-submenu" onClick={() => setCompanyOpen(!companyExpanded)} className={`flex w-full items-center justify-between gap-3 rounded-lg px-3.5 py-2.5 text-sm font-medium transition-all duration-200 ${isCompanyActive || companyExpanded ? "bg-white/15 text-white shadow-lg shadow-black/10 backdrop-blur-sm" : "text-white/60 hover:bg-white/8 hover:text-white/90"}`}>
                    <span className="flex items-center gap-3"><Building2 className="h-[18px] w-[18px]" />Company</span>
                    {companyExpanded ? <ChevronDown className="h-4 w-4 text-white/40" /> : <ChevronRight className="h-4 w-4 text-white/40" />}
                  </button>
                  {companyExpanded && <div id="company-submenu" className="ml-4 mt-1 space-y-0.5 border-l border-white/10 pl-3">
                    <Link href="/companies" onClick={() => setSidebarOpen(false)} className={`flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-all duration-200 ${pathname.startsWith("/companies") ? "bg-white/15 text-white" : "text-white/50 hover:bg-white/8 hover:text-white/80"}`}><Building2 className="h-4 w-4" />Companies</Link>
                    {canPage("/manage-users") && <Link href="/manage-users?context=company" onClick={() => setSidebarOpen(false)} className={`flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-all duration-200 ${companyUsersActive ? "bg-white/15 text-white" : "text-white/50 hover:bg-white/8 hover:text-white/80"}`}><Users className="h-4 w-4" />Users</Link>}
                  </div>}
                </div>
              );
            }
            const isActive =
              pathname === item.href ||
              (item.href === "/dashboard" && pathname === "/") ||
              (item.href === "/products" && pathname.startsWith("/products")) ||
              (item.href === "/stock-management" && pathname.startsWith("/stock-management")) ||
              (item.href === "/orders" && pathname.startsWith("/orders") && pathname !== "/orders/new") ||
              (item.href === "/orders/new" && pathname === "/orders/new") ||
              (item.href === "/delivery-management" && pathname.startsWith("/delivery-management")) ||
              (item.href === "/mis-reporting" && pathname.startsWith("/mis-reporting")) ||
              (item.href === "/notifications" && pathname.startsWith("/notifications"));
            return (
              <Link
                key={item.name}
                href={item.href}
                onClick={() => setSidebarOpen(false)}
                className={`flex items-center gap-3 rounded-lg px-3.5 py-2.5 text-sm font-medium transition-all duration-200 ${
                  isActive
                    ? "bg-white/15 text-white shadow-lg shadow-black/10 backdrop-blur-sm"
                    : "text-white/60 hover:bg-white/8 hover:text-white/90"
                }`}
              >
                <item.icon
                  className={`h-[18px] w-[18px] ${
                    isActive ? "text-white" : "text-white/40"
                  }`}
                />
                {displayValue(item.name)}
              </Link>
            );
          })}

          {/* Permissions Dropdown (Super Admin only) */}
          {hasPermissionItems && (
            <div className="mt-3 pt-3 border-t border-white/10">
              <button
                onClick={() => setPermissionsOpen(!permissionsOpen)}
                className={`flex w-full items-center justify-between gap-3 rounded-lg px-3.5 py-2.5 text-sm font-medium transition-all duration-200 ${
                  isPermissionsActive || permissionsOpen
                    ? "bg-white/15 text-white shadow-lg shadow-black/10 backdrop-blur-sm"
                    : "text-white/60 hover:bg-white/8 hover:text-white/90"
                }`}
              >
                <div className="flex items-center gap-3">
                  <Settings
                    className={`h-[18px] w-[18px] ${
                      isPermissionsActive || permissionsOpen ? "text-white" : "text-white/40"
                    }`}
                  />
                  Permissions
                </div>
                {permissionsOpen ? (
                  <ChevronDown className="h-4 w-4 text-white/40" />
                ) : (
                  <ChevronRight className="h-4 w-4 text-white/40" />
                )}
              </button>

              {/* Dropdown items */}
              {permissionsOpen && (
                <div className="ml-4 mt-1 space-y-0.5 border-l border-white/10 pl-3">
                  {allowedPermissionItems.map((item) => {
                    const isActive = pathname === item.href && !(item.href === "/manage-users" && companyUsersActive);
                    return (
                      <Link
                        key={item.name}
                        href={item.href}
                        onClick={() => setSidebarOpen(false)}
                        className={`flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-all duration-200 ${
                          isActive
                            ? "bg-white/15 text-white"
                            : "text-white/50 hover:bg-white/8 hover:text-white/80"
                        }`}
                      >
                        <item.icon
                          className={`h-4 w-4 ${
                            isActive ? "text-white" : "text-white/30"
                          }`}
                        />
                        {displayValue(item.name)}
                      </Link>
                    );
                  })}
                </div>
              )}
            </div>
          )}
        </nav>

        {/* User section */}
        <div className="border-t border-white/10 p-4">
          <div className="flex items-center gap-3">
            <div className="flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-full bg-white/15 text-xs font-bold text-white backdrop-blur-sm">
              {getUserInitials(userName)}
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-sm font-medium text-white truncate">{userName}</p>
              <p className="text-xs text-white/40 truncate capitalize">
                {roleName}
              </p>
            </div>
            <button
              onClick={() => logout()}
              disabled={logoutLoading}
              className="text-white/30 hover:text-white/70 transition-colors disabled:opacity-50 rounded-lg p-1.5 hover:bg-white/10"
              title="Logout"
            >
              <LogOut className="h-4 w-4" />
            </button>
          </div>
        </div>
      </aside>

      {/* ============================================ */}
      {/* Main Content Area */}
      {/* ============================================ */}
      <div className="flex min-w-0 flex-1 flex-col overflow-hidden">
        {/* Top Header */}
        <header className="flex h-16 items-center justify-between border-b border-gray-200/80 bg-white/80 backdrop-blur-md px-6">
          <div className="flex items-center gap-4">
            <button
              onClick={() => setSidebarOpen(true)}
              className="text-gray-400 hover:text-gray-600 lg:hidden"
            >
              <Menu className="h-5 w-5" />
            </button>
            {/* Welcome text */}
            <div>
              <p className="text-sm text-gray-500">
                Welcome Back, <span className="font-semibold text-navy-900">{userName}!</span>
              </p>
            </div>
          </div>
          <div className="flex items-center gap-3">
            {/* Cart Icon — only for department_user */}
            {can("orders.create") && (
              <Link
                href="/cart"
                className="relative inline-flex items-center gap-1.5 rounded-lg border border-gray-200 bg-white px-3 py-2 text-sm font-medium text-gray-700 shadow-sm transition-colors hover:bg-gray-50 hover:text-gray-900"
              >
                <ShoppingCart className="h-4 w-4" />
                <span className="hidden sm:inline">Cart</span>
                {cartItemCount > 0 && (
                  <span className="absolute -right-2 -top-2 flex h-5 min-w-5 items-center justify-center rounded-full bg-navy-900 px-1 text-[10px] font-bold text-white shadow-sm">
                    {cartItemCount > 99 ? "99+" : cartItemCount}
                  </span>
                )}
              </Link>
            )}
            {/* View Profile */}
            <Link
              href="/manage-profile"
              className="inline-flex items-center gap-2 rounded-lg border border-gray-200 bg-white px-3.5 py-2 text-sm font-medium text-gray-700 shadow-sm hover:bg-gray-50 hover:text-gray-900 transition-colors"
            >
              <UserCog className="h-4 w-4" />
              View Profile
            </Link>
          </div>
        </header>

        {/* Page Content */}
        <main className="flex-1 overflow-y-auto p-6">{children}</main>
      </div>
    </div>
  );
}
