import List from "@mui/material/List";
import Divider from "@mui/material/Divider";
import { authStore, NAVIGATION_ITEMS, ROUTE_REQUIRED_RESOURCES } from "@shared";
import { NavigationItem, NavigationItemComponent } from "@entities";
import { observer } from "mobx-react-lite";

interface NavigationListProps {
  open: boolean;
  onDrawerOpen?: () => void;
}

const isItemVisible = (item: (typeof NAVIGATION_ITEMS.primary)[number]): boolean => {
  // Для карты в навигации требуем наличие ВСЕХ трёх rw-ролей: routes/stations/sights
  if (item.id === "map") {
    return ["routes", "stations", "sights"].every((resource) =>
      authStore.canWrite(resource),
    );
  }

  // Пользователь с ролью ТО всегда видит раздел устройств
  if (item.path === "/devices" && authStore.hasRole("devices_maintenance_rw")) {
    return true;
  }

  const routePermissions = item.path ? ROUTE_REQUIRED_RESOURCES[item.path] ?? [] : [];
  const canAccessRoute = routePermissions.every((permission) =>
    authStore.canAccess(permission),
  );

  if (!canAccessRoute) {
    return false;
  }

  if (!item.requiredRoles || item.requiredRoles.length === 0) {
    return true;
  }

  return item.requiredRoles.some((role) => {
    const match = role.match(/^(.+)_r[ow]$/);
    if (match) {
      return authStore.canRead(match[1]);
    }
    return authStore.hasRole(role);
  });
};

export const NavigationList = observer(
  ({ open, onDrawerOpen }: NavigationListProps) => {
    const primaryItems = NAVIGATION_ITEMS.primary
      .filter(isItemVisible)
      .map((item) => {
        if (!item.nestedItems) return item;
        return {
          ...item,
          nestedItems: item.nestedItems.filter(isItemVisible),
        };
      })
      .filter((item) => !item.nestedItems || item.nestedItems.length > 0);

    return (
      <>
        <List>
          {primaryItems.map((item) => (
            <NavigationItemComponent
              key={item.id}
              item={item as NavigationItem}
              open={open}
              onDrawerOpen={onDrawerOpen}
            />
          ))}
        </List>
        <Divider />
        <List>
          {NAVIGATION_ITEMS.secondary.map((item) => (
            <NavigationItemComponent
              key={item.id}
              item={item as NavigationItem}
              open={open}
              onClick={item.onClick ?? undefined}
              onDrawerOpen={onDrawerOpen}
            />
          ))}
        </List>
      </>
    );
  }
);
