import { NavLink, useParams } from "react-router-dom";
import { useAuth } from "@/shared/context/AuthContext";
import { useTranslation } from "react-i18next";
import { useState } from "react";

import { ScrollArea } from "@/shared/common/ui/scroll-area";

// Icons
import {
  ChevronDown,
  ChevronRight,
  Home,
  TableProperties,
  Calendar,
} from "lucide-react";
import { MenuItem as BaseMenuItem } from "@/layout/AppMenuTabs";
import { FaTasks } from "react-icons/fa";
import { getSelectedPositionType } from "@/performance-management/utils/positionTypeUtils";
import { EPositionTypeKey } from "@/shared/dto/user/meDto";
import { checkIsPlanInitiator } from "@/performance-management/hooks/usePlans";

// Extended MenuItem interface with position type support
interface MenuItem extends BaseMenuItem {
  positionTypes?: EPositionTypeKey[];
}

interface PerformanceMenuTablsProps {
  collapsed?: boolean;
  toggleSidebar?: () => void;
}

export const PerformanceMenuTabls = ({
  collapsed = false,
}: PerformanceMenuTablsProps) => {
  const { user, selectedPositionId } = useAuth();
  const userRoles = user?.roles.map((role) => role.key) || [];
  const userPositionType = getSelectedPositionType(user, selectedPositionId);
  const isPlanInitiator = checkIsPlanInitiator(
    user,
    selectedPositionId || undefined,
  );

  // Debug: log user roles and position type
  console.log("User roles:", userRoles);
  console.log("User position type:", userPositionType);
  console.log("Has empty role:", userRoles.includes(""));

  const { t } = useTranslation();
  const [openDropdown, setOpenDropdown] = useState<string | null>(null);

  const toggleDropdown = (label: string) => {
    setOpenDropdown((prev) => (prev === label ? null : label));
  };
  const { yearId } = useParams<{ yearId: string }>();

  // Year-independent menu items (always visible)
  const yearIndependentItems: MenuItem[] = [
    {
      label: "Plan Years",
      href: "/performance-management/plan-years",
      icon: <Calendar className="h-4 w-4" />,
      roles: ["super_admin", "unit_admin", ""],
      isPrimary: true,
    },

    {
      label: "Service Categories",
      href: "/performance-management/service-categories",
      icon: <TableProperties className="h-4 w-4" />,
      roles: ["super_admin", "unit_admin", "user"],
      isPrimary: true,
    },
    {
      label: "Services",
      href: `/performance-management/services`,
      icon: <TableProperties className="h-4 w-4" />,
      roles: ["super_admin", "unit_admin", "user"],
      isPrimary: true,
    },
    {
      label: "Service Assignment",
      href: `/performance-management/service-assignment`,
      icon: <TableProperties className="h-4 w-4" />,
      roles: ["super_admin", "unit_admin", "user"],
      isPrimary: true,
    },
    {
      label: "Active Call Management",
      href: `/performance-management/active-call-management`,
      icon: <TableProperties className="h-4 w-4" />,
      roles: [""],
      positionTypes: [EPositionTypeKey.EMPLOYEE],
      isPrimary: true,
    },
  ];

  // Year-dependent menu items (only visible when yearId exists)
  const yearDependentItems: MenuItem[] = [
    {
      label: "dashboard",
      href: `/performance-management/${yearId}/dashboard`,
      icon: <Home className="h-4 w-4" />,
      roles: ["super_admin", "unit_admin", ""],
      isPrimary: true,
    },
    {
      label: "Plans",
      href: `/performance-management/${yearId}/${
        isPlanInitiator ? "plans" : "my-plans"
      }`,
      icon: <TableProperties className="h-4 w-4" />,
      roles: [""],
      positionTypes: [
        EPositionTypeKey.DIRECTOR,
        EPositionTypeKey.DEPUTY,
        EPositionTypeKey.OFFICE_HEAD,
        EPositionTypeKey.BUDGET_PLAN,
      ],
      isPrimary: true,
    },
    {
      label: "Employee Plans",
      href: `/performance-management/${yearId}/employee-plans`,
      icon: <FaTasks className="h-4 w-4" />,
      roles: ["super_admin", "unit_admin", ""],
      // Employee Plans is relevant for anyone who can be assigned monthly
      // tasks, which is effectively every employee position. Leaving the
      // positionTypes filter off avoids hiding the link when the backend
      // returns a positionType.key that doesn't match the enum (e.g. an
      // unexpected key would otherwise hide the item entirely).
      isPrimary: true,
    },
    {
      label: "Team Member Management",
      href: `/performance-management/${yearId}/team-member-management`,
      icon: <FaTasks className="h-4 w-4" />,
      roles: ["super_admin", "unit_admin", ""],
      isPrimary: true,
    },
  ];

  // Filter items based on user roles and position types
  const filterByRoles = (items: MenuItem[]) => {
    return items.filter((item) => {
      // Check role requirements
      let hasRole = true;
      if (item.roles && item.roles.length > 0) {
        hasRole = item.roles.some((role) => userRoles.includes(role));

        // Special case: If item allows "" (empty string role), it should ALSO match users with NO roles ([])
        if (item.roles.includes("") && userRoles.length === 0) {
          hasRole = true;
        }
      }

      // Check position type requirements
      let hasPositionType = true;
      if (item.positionTypes && item.positionTypes.length > 0) {
        hasPositionType = userPositionType
          ? item.positionTypes.includes(userPositionType)
          : false;
      }

      // User must satisfy both role AND position type requirements (if they exist)
      return hasRole && hasPositionType;
    });
  };

  // Combine and filter menu items based on whether yearId exists and user roles
  const filteredMenu = yearId
    ? filterByRoles([...yearIndependentItems, ...yearDependentItems])
    : filterByRoles(yearIndependentItems);

  const primaryMenu = filteredMenu.filter((i) => i.isPrimary);
  const secondaryMenu = filteredMenu.filter((i) => !i.isPrimary);
  const renderChildren = (children: MenuItem[]) => {
    return (
      <div className="ml-8 mt-1 space-y-1">
        {children.map((child) => (
          <NavLink
            key={child.href}
            to={child.href!}
            className={({ isActive }) =>
              `block px-3 py-2 text-sm rounded-md transition-colors ${
                isActive
                  ? "bg-purple-100 text-purple-700 dark:bg-purple-900 dark:text-purple-300"
                  : "text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-800"
              }`
            }
          >
            {t(`organization.${child.label}`)}
          </NavLink>
        ))}
      </div>
    );
  };

  // ---- MAIN RETURN ----
  return (
    <>
      {/* --------------------- MOBILE TABS --------------------- */}
      <div className="md:hidden fixed top-16 left-0 right-0 z-30 bg-white dark:bg-gray-900 border-b dark:border-gray-800 pt-5 pb-3 px-4 space-y-3">
        {/* Primary row */}
        <div className="flex items-center overflow-x-auto scrollbar-none">
          {primaryMenu.map((item) => (
            <NavLink
              key={item.href}
              to={item.href!}
              className={({ isActive }) => {
                // Custom active check: for Plans, match /plans, /plans-table, /my-plans, or /plan/{id}
                let isItemActive = isActive;
                if (item.label === "Plans") {
                  const currentPath = window.location.pathname;
                  isItemActive =
                    currentPath.includes("/my-plans") ||
                    currentPath.includes("/plan/") ||
                    currentPath.includes("/plans");
                }

                return `flex items-center gap-1 px-3 py-2.5 mr-2 text-xs font-medium ${
                  isItemActive
                    ? "text-[#A043F0] border-b-2 border-[#A043F0]"
                    : "text-slate-700 hover:text-[#A043F0]"
                }`;
              }}
            >
              {item.icon}
              <span className="max-w-[80px] truncate">
                {t(`organization.${item.label}`)}
              </span>
            </NavLink>
          ))}
        </div>

        {/* Secondary row */}
        {secondaryMenu.length > 0 && (
          <div className="flex items-center overflow-x-auto border-t pt-3">
            {secondaryMenu.map((item) => (
              <NavLink
                key={item.label}
                to={item.href || "#"}
                className="flex items-center gap-1 px-3 py-2.5 mr-2 text-xs font-medium text-slate-700 hover:text-[#A043F0]"
              >
                {item.icon}
                <span className="max-w-[80px] truncate">
                  {t(`organization.${item.label}`)}
                </span>
              </NavLink>
            ))}
          </div>
        )}
      </div>

      {/* --------------------- DESKTOP SIDEBAR --------------------- */}
      <div className="hidden md:flex flex-col h-full">
        <ScrollArea className="flex-1">
          <div className="mt-4 space-y-1">
            {filteredMenu.map((item) => {
              // ---------- PARENT WITH CHILDREN ----------
              if (item.children && item.children.length > 0) {
                const isOpen = openDropdown === item.label;

                return (
                  <div key={item.label} className="mx-2">
                    {/* Parent row */}
                    <button
                      onClick={() => toggleDropdown(item.label)}
                      className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg transition-colors text-left ${
                        isOpen
                          ? "bg-purple-100 text-purple-700 dark:bg-purple-900 dark:text-purple-300"
                          : "text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-800"
                      } ${collapsed ? "justify-center" : ""}`}
                    >
                      {item.icon}
                      {!collapsed && (
                        <>
                          <span className="font-medium whitespace-nowrap">
                            {t(`organization.${item.label}`)}
                          </span>
                          <div className="ml-auto">
                            {isOpen ? (
                              <ChevronDown className="h-4 w-4" />
                            ) : (
                              <ChevronRight className="h-4 w-4" />
                            )}
                          </div>
                        </>
                      )}
                    </button>

                    {/* Children */}
                    {!collapsed && isOpen && renderChildren(item.children)}
                  </div>
                );
              }

              // ---------- REGULAR ITEM ----------
              return (
                <NavLink
                  key={item.href}
                  to={item.href!}
                  className={({ isActive }) => {
                    // Custom active check: for Plans, check if path contains /my-plans or /plan/
                    let isItemActive = isActive;
                    if (item.label === "Plans") {
                      const currentPath = window.location.pathname;
                      isItemActive =
                        currentPath.includes("/my-plans") ||
                        currentPath.includes("/plan/");
                    }

                    return `flex items-center gap-3 px-3 py-2.5 mx-2 rounded-lg transition-colors ${
                      isItemActive
                        ? "bg-purple-100 text-purple-700 dark:bg-purple-900 dark:text-purple-300"
                        : "text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-800"
                    } ${collapsed ? "justify-center" : ""}`;
                  }}
                >
                  {item.icon}
                  {!collapsed && (
                    <span className="font-medium whitespace-nowrap">
                      {t(`organization.${item.label}`)}
                    </span>
                  )}
                </NavLink>
              );
            })}
          </div>
        </ScrollArea>
      </div>
    </>
  );
};
