"use client";

import Link from "next/link";
import { useDashboard } from "@/features/dashboard/hooks/use-dashboard";
import { usePathname } from "next/navigation";
import { useState, useEffect, useMemo } from "react";
import { useLogout } from "@/features/auth/hooks/use-logout";
import { useCartContext } from "@/features/cart/components/cart-context";
import {
  LayoutDashboard,
  Building2,
  Package,
  ShoppingCart,
  Truck,
  LogOut,
  Bell,
  Menu,
  X,
  Shield,
  UserCog,
  ChevronDown,
  ChevronRight,
  Settings,
  Users,
  Boxes,
  BarChart3,
  CreditCard,
} from "lucide-react";
import type { SystemRole, SidebarPermission } from "@/features/manage-users/dtos/manage-users.dto";

// ============================================
// Role → Permission Mapping
// ============================================

const ROLE_PERMISSIONS: Record<SystemRole, SidebarPermission[]> = {
  super_admin: [
    "/dashboard",
    "/companies",
    "/products",
    "/stock-management",
    "/orders",
    "/orders/new",
    "/delivery-management",
    "/mis-reporting",
    "/notifications",
    "/manage-profile",
    "/manage-roles",
    "/manage-users",
  ],
  it_team: [
    "/dashboard",
    "/companies",
    "/notifications",
    "/manage-profile",
  ],
  delivery_management: [
    "/dashboard",
    "/stock-management",
    "/delivery-management",
    "/mis-reporting",
    "/notifications",
    "/manage-profile",
  ],
  department_user: [
    "/dashboard",
    "/orders",
    "/orders/new",
    "/notifications",
    "/manage-profile",
  ],
};

// ============================================
// Navigation Config (full list — filtered by role)
// ============================================

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: "Business Cards", href: "/business-card", icon: CreditCard },
  { name: "Stock Management", href: "/stock-management", icon: Boxes },
  { name: "Orders", href: "/orders", icon: ShoppingCart },
  { name: "New Order", href: "/orders/new", icon: Package },
  { name: "Delivery Management", href: "/delivery-management", icon: Truck },
  { 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 getCurrentUserRole(): SystemRole | null {
  if (typeof window === "undefined") return null;
  const role = localStorage.getItem("current_user_role");
  if (role && ROLE_PERMISSIONS[role as SystemRole]) {
    return role as SystemRole;
  }
  return null;
}

function getCurrentUserName(): string {
  if (typeof window === "undefined") return "User";
  return localStorage.getItem("current_user_name") || "User";
}

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;
}

export function AdminLayout({ children }: AdminLayoutProps) {
  const { data: navigationData } = useDashboard();
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [permissionsOpen, setPermissionsOpen] = useState(false);
  const [currentRole, setCurrentRole] = useState<SystemRole | null>(null);
  const [userName, setUserName] = useState("User");
  const pathname = usePathname();
  const { logout, loading: logoutLoading } = useLogout();
  const { itemCount: cartItemCount } = useCartContext();

  // Read role from localStorage on mount
  useEffect(() => {
    setCurrentRole(getCurrentUserRole());
    setUserName(getCurrentUserName());

    // Listen for storage changes (e.g., after login in another tab)
    const handleStorageChange = (): void => {
      setCurrentRole(getCurrentUserRole());
      setUserName(getCurrentUserName());
    };
    window.addEventListener("storage", handleStorageChange);
    return () => window.removeEventListener("storage", handleStorageChange);
  }, []);

  // Compute allowed navigation items based on role
  const allowedNavigation = useMemo(() => {
    if (!currentRole) return allNavigation; // Fallback: show all if no role set
    const permissions = ROLE_PERMISSIONS[currentRole];
    return allNavigation.filter((item) => item.href === "/business-card"
      ? navigationData?.quickLinks.includes(item.href) === true
      : permissions.includes(item.href));
  }, [currentRole, navigationData]);

  // Check if user has any permission nav items
  const hasPermissionItems = useMemo(() => {
    if (!currentRole) return false;
    const permissions = ROLE_PERMISSIONS[currentRole];
    return permissionNavItems.some((item) => permissions.includes(item.href));
  }, [currentRole]);

  // Check if user has manage-roles or manage-users access
  const allowedPermissionItems = useMemo(() => {
    if (!currentRole) return permissionNavItems;
    const permissions = ROLE_PERMISSIONS[currentRole];
    return permissionNavItems.filter((item) => permissions.includes(item.href));
  }, [currentRole]);

  // Check if any sub-item under Permissions is active
  const isPermissionsActive = useMemo(() => {
    return pathname === "/manage-roles" || pathname === "/manage-users";
  }, [pathname]);

  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">
            <h2
              className="text-2xl font-extrabold tracking-wider text-white"
              style={{ fontFamily: "Georgia, 'Times New Roman', serif" }}
            >
              SINGH
            </h2>
          </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) => {
            const isActive =
              pathname === item.href ||
              (item.href === "/dashboard" && pathname === "/") ||
              (item.href === "/companies" && pathname.startsWith("/companies")) ||
              (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"
                  }`}
                />
                {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;
                    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"
                          }`}
                        />
                        {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">
                {currentRole?.replace("_", " ") || "Admin"}
              </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 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 super_admin and department_user */}
            {(currentRole === "super_admin" || currentRole === "department_user") && (
              <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>
  );
}
