// Sidebar.tsx
import { createElement, useEffect, useMemo, useState } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { useAuth } from "../../hooks/useAuth";
import { X } from "lucide-react";
import { Menu, Layout } from "antd";
import type { MenuProps } from "antd";
import { NAV_LINKS, Role } from "../../constants/navLink.constants";
import ROUTE_CONSTANTS from "../../constants/route.constants";

const { Sider } = Layout;

interface SidebarProps {
  isOpen: boolean;
  onClose: () => void;
}

const Sidebar: React.FC<SidebarProps> = ({ isOpen, onClose }) => {
  const { user } = useAuth();
  const navigate = useNavigate();
  const location = useLocation();
  const [openKeys, setOpenKeys] = useState<string[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);

  const filterNavItems = (
    items: any[],
    userRole: Role,
    permissions: string[],
  ): any[] => {
    return items.reduce((acc, item) => {
      // Check if current item is allowed
      const isAllowed =
        userRole === Role.STAFF
          ? permissions.includes(item.permissionKey)
          : item.roles.includes(userRole);

      // If item has children, filter them recursively
      if (item.children) {
        const filteredChildren = filterNavItems(
          item.children,
          userRole,
          permissions,
        );
        // Only include parent if it has accessible children or if it's explicitly allowed itself (and is a leaf or group header)
        // But for menus, usually if children are empty, we hide the group.
        if (filteredChildren.length > 0) {
          acc.push({ ...item, children: filteredChildren });
        }
      } else if (isAllowed) {
        // Leaf node, just push if allowed
        acc.push(item);
      }
      return acc;
    }, []);
  };

  const navItems = useMemo(() => {
    if (!user) return [];
    const staffPermissions = Array.isArray(user?.permissions)
      ? [...user.permissions, "allUsers"]
      : ["allUsers"];

    return filterNavItems(NAV_LINKS, user.role as Role, staffPermissions);
  }, [user]);

  const hrefParentMap = useMemo(() => {
    const map = new Map<string, string[]>();

    const walk = (items: any[], parents: string[] = []) => {
      for (const item of items) {
        map.set(item.href, parents);
        if (item.children) {
          walk(item.children, [...parents, item.href]);
        }
      }
    };

    walk(navItems);
    return map;
  }, [navItems]);

  useEffect(() => {
    if (navItems.length === 0) return;

    const sel = selectedKeyFromPath(location.pathname);
    setSelectedKeys(sel ? [sel] : []);
    if (sel) {
      setOpenKeys(hrefParentMap.get(sel) || []);
    }
  }, [navItems, location.pathname, hrefParentMap]);

  const selectedKeyFromPath = (path: string): string | null => {
    if (!path) return null;
    const normalizedPath = path === "/" ? "/" : path.replace(/\/$/, "");

    if (normalizedPath.startsWith("/progress-overview/performance")) {
      return ROUTE_CONSTANTS.ProgressOverview;
    }

    let bestMatchKey: string | null = null;
    let maxMatchLength = -1;

    for (const href of hrefParentMap.keys()) {
      const normalizedHref = href === "/" ? "/" : href.replace(/\/$/, "");

      // Handle exact match
      if (normalizedPath === normalizedHref) {
        return href;
      }

      // Handle child path match (parent highlighting)
      if (
        normalizedHref !== "/" &&
        normalizedPath.startsWith(normalizedHref + "/")
      ) {
        if (normalizedHref.length > maxMatchLength) {
          maxMatchLength = normalizedHref.length;
          bestMatchKey = href;
        }
      }
    }

    // Special case for root
    if (!bestMatchKey && normalizedPath === "/") {
      return hrefParentMap.has("/") ? "/" : null;
    }

    return bestMatchKey;
  };

  const buildMenuItems = (items: any[]): MenuProps["items"] =>
    items.map((item) => {
      if (item.children && item.children.length) {
        return {
          key: item.href,
          icon: createElement(item.icon, {
            className: "h-5 w-5 text-gray-300",
          }),
          label: <span className="text-wrap leading-tight">{item.name}</span>,
          children: buildMenuItems(item.children),
          title: item.name,
        };
      }
      return {
        key: item.href,
        icon: createElement(item.icon, {
          className: "h-5 w-5 text-gray-300",
        }),
        label: <span className="text-wrap leading-tight">{item.name}</span>,
        title: item.name,
      };
    });

  const menuItems = useMemo(() => buildMenuItems(navItems), [navItems]);

  const onOpenChange: MenuProps["onOpenChange"] = (keys) => {
    setOpenKeys(keys as string[]);
  };

  const handleMenuClick: MenuProps["onClick"] = ({ key }) => {
    const href = String(key);
    navigate(href);
    const sel = selectedKeyFromPath(href) ?? href;
    setSelectedKeys([sel]);
    setOpenKeys(hrefParentMap.get(sel) ?? []);
    if (window.innerWidth < 768) onClose();
  };

  return (
    <Sider
      width={260}
      collapsedWidth={0}
      className={`h-full fixed inset-y-0 left-0 z-40 transform transition-transform duration-300 ease-in-out 
        ${isOpen ? "translate-x-0" : "-translate-x-full"} 
        md:relative md:translate-x-0 
        bg-brand-navy`}
    >
      {/* Header */}
      <div className="w-full flex items-center justify-center h-[4.75rem] px-5 border-b border-gray-700/40 gap-2">
        <img src="/logo_horizantal.png" alt="logo" className="h-10" />
        {/* <h1 className="text-2xl font-semibold text-gray-100 tracking-wide">
          ExamInfra
        </h1> */}
        <button
          onClick={onClose}
          className="md:hidden text-gray-400 hover:text-gray-200"
          aria-label="Close sidebar"
        >
          <X className="h-6 w-6" />
        </button>
      </div>

      {/* Menu */}
      <div className="overflow-auto h-[calc(100vh-120px)] px-2 py-3 custom-scrollbar">
        <Menu
          mode="inline"
          items={menuItems}
          selectedKeys={selectedKeys}
          openKeys={openKeys}
          onOpenChange={onOpenChange}
          onClick={handleMenuClick}
          className="glassy-menu !border-none !bg-transparent"
          style={{ color: "#E5E7EB" }}
        />
      </div>

      <style>{`
        .glassy-menu .ant-menu-item,
        .glassy-menu .ant-menu-submenu-title {
          border-radius: 10px;
          margin: 4px 8px;
          transition: all 0.3s ease;
          color: #bfdbfe;
          height: auto !important;
          line-height: normal !important;
          padding-top: 8px !important;
          padding-bottom: 8px !important;
          display: flex !important;
          align-items: center !important;
        }

        .glassy-menu .ant-menu-title-content {
          white-space: normal !important;
          line-height: 1.4 !important;
        }

        .glassy-menu .ant-menu-item:hover {
          color: #fff !important;
          background: #ffffff1a !important;
        }

        .glassy-menu .ant-menu-item-selected {
          color: #fff !important;
          background: #f97316 !important;

          &:hover {
            background: #f97316 !important;
          }
        }

        .glassy-menu .ant-menu-submenu-title {
          color: #d1d5db !important;
        }

        .custom-scrollbar::-webkit-scrollbar {
          width: 5px;
        }

        .custom-scrollbar::-webkit-scrollbar-thumb {
          background: #6b7280;
          border-radius: 4px;
        }
      `}</style>
    </Sider>
  );
};

export default Sidebar;
