import { Link, useLocation } from "react-router-dom";
import {
  Archive,
  BarChart,
  Building2,
  ChartAreaIcon,
  ClipboardList,
  FileText,
  Globe,
  MapPin,
  Settings,
  Users2,
  UsersRound,
} from "lucide-react";
import { useTranslation } from "react-i18next";

import { useAuth } from "@/shared/context/AuthContext";
import {
  SidebarGroup,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  useSidebar,
} from "@/shared/common/ui/sidebar";

export interface MenuItem {
  label: string;
  href: string;
  icon: React.ReactNode;
  roles?: string[];
  /** Sidebar section this item is bucketed under. */
  group: string;
}

// Section render order; groups with no role-visible items are skipped.
const GROUP_ORDER = [
  "Overview",
  "Organizations",
  "Content",
  "Records",
  "Configuration",
  "Archive",
  "System",
];

export const AppMenuTabs = () => {
  const { user } = useAuth();
  const { pathname } = useLocation();
  const { setOpenMobile } = useSidebar();
  const { t } = useTranslation();

  const userRoles = user?.roles.map((role) => role.key) || [];

  const menuItems: MenuItem[] = [
    {
      label: "dashboard",
      href: "/user-management/dashboard",
      icon: <BarChart className="h-4 w-4" />,
      roles: ["super_admin"],
      group: "Overview",
    },
    {
      label: "organizations",
      href: "/user-management/organizations",
      icon: <Building2 className="h-4 w-4" />,
      roles: ["super_admin"],
      group: "Organizations",
    },
    {
      label: "organizationAdmins",
      href: "/user-management/organization_admins",
      icon: <Users2 className="h-4 w-4" />,
      roles: ["super_admin"],
      group: "Organizations",
    },
    {
      label: "externalUsers",
      href: "/user-management/external_users",
      icon: <Users2 className="h-4 w-4" />,
      roles: ["super_admin"],
      group: "Organizations",
    },
    {
      label: "dashboard",
      href: "/user-management/user_management-dashboard",
      icon: <BarChart className="h-4 w-4" />,
      roles: ["admin", "organization_admin", "unit_admin"],
      group: "Overview",
    },
    {
      label: "userManagement",
      href: "/user-management/user_management",
      icon: <UsersRound className="h-4 w-4" />,
      roles: ["admin", "organization_admin", "unit_admin"],
      group: "Overview",
    },
    {
      label: "contentManagement",
      href: "/user-management/content-management",
      icon: <FileText className="h-4 w-4" />,
      roles: ["admin", "organization_admin", "unit_admin"],
      group: "Content",
    },
    {
      label: "webManagement",
      href: "/user-management/web-management",
      icon: <Globe className="h-4 w-4" />,
      roles: ["admin", "organization_admin", "unit_admin"],
      group: "Content",
    },
    {
      label: "Bulk",
      href: "/user-management/bulk-upload",
      icon: <FileText className="h-4 w-4" />,
      roles: ["admin", "organization_admin", "unit_admin"],
      group: "Content",
    },
    {
      label: "Position",
      href: "/user-management/position-management",
      icon: <FileText className="h-4 w-4" />,
      roles: ["admin", "organization_admin", "unit_admin", "super_admin"],
      group: "Configuration",
    },
    {
      label: "Locations",
      href: "/user-management/locations",
      icon: <MapPin className="h-4 w-4" />,
      roles: ["admin", "organization_admin", "unit_admin", "super_admin"],
      group: "Configuration",
    },
    {
      label: "settings",
      href: "/user-management/organization-settings",
      icon: <Settings className="h-4 w-4" />,
      roles: ["admin", "organization_admin", "unit_admin"],
      group: "Configuration",
    },
    {
      label: "Add Site",
      href: "/user-management/add-site",
      icon: <Globe className="h-4 w-4" />,
      roles: ["super_admin"],
      group: "Configuration",
    },
    {
      label: "migratedRecords",
      href: "/user-management/migrated-records-management",
      icon: <FileText className="h-4 w-4" />,
      roles: ["super_admin"],
      group: "Records",
    },
    {
      label: "Sector Reports",
      href: "/user-management/sector-reports",
      icon: <ChartAreaIcon className="h-4 w-4" />,
      roles: ["unit_admin", "admin", "organization_admin"],
      group: "Records",
    },
    {
      label: "Archive Users",
      href: "/user-management/archive-users",
      icon: <Archive className="h-4 w-4" />,
      roles: ["super_admin"],
      group: "Archive",
    },
    {
      label: "Archived Organizations",
      href: "/user-management/archived-organizations",
      icon: <Archive className="h-4 w-4" />,
      roles: ["super_admin"],
      group: "Archive",
    },
    {
      label: "Archive Users",
      href: "/user-management/archives",
      icon: <Archive className="h-4 w-4" />,
      roles: ["admin", "organization_admin", "unit_admin"],
      group: "Archive",
    },
    {
      label: "Archived Units & Positions",
      href: "/user-management/archived",
      icon: <Archive className="h-4 w-4" />,
      roles: ["admin", "organization_admin", "unit_admin"],
      group: "Archive",
    },
    {
      label: "activityLog",
      href: "/user-management/activity_log",
      icon: <ClipboardList className="h-4 w-4" />,
      roles: ["super_admin"],
      group: "System",
    },
    {
      label: "setting",
      href: "/user-management/settings",
      icon: <Settings className="h-4 w-4" />,
      roles: ["super_admin"],
      group: "System",
    },
    {
      label: "Letter Template",
      href: "/user-management/templates",
      icon: <FileText className="h-4 w-4" />,
      roles: ["super_admin"],
      group: "System",
    },
  ];

  const filteredMenu = menuItems.filter((item) =>
    item.roles?.some((r) => userRoles.includes(r)),
  );

  const isActive = (href: string) =>
    pathname === href || pathname.startsWith(`${href}/`);

  return (
    <>
      {GROUP_ORDER.map((group) => {
        const items = filteredMenu.filter((item) => item.group === group);
        if (items.length === 0) return null;

        return (
          <SidebarGroup key={group} className="pb-0">
            <SidebarGroupLabel>{group}</SidebarGroupLabel>
            <SidebarGroupContent>
              <SidebarMenu>
                {items.map((item) => {
                  const label = t(`organization.${item.label}`, item.label);
                  return (
                    <SidebarMenuItem key={item.href}>
                      <SidebarMenuButton
                        asChild
                        isActive={isActive(item.href)}
                        tooltip={label}
                      >
                        <Link
                          to={item.href}
                          onClick={() => setOpenMobile(false)}
                        >
                          {item.icon}
                          <span>{label}</span>
                        </Link>
                      </SidebarMenuButton>
                    </SidebarMenuItem>
                  );
                })}
              </SidebarMenu>
            </SidebarGroupContent>
          </SidebarGroup>
        );
      })}
    </>
  );
};
