import { shellApi } from "../../api/api";
import { ExitShell } from "../../features/exit/request";
import { CommunicationActionMenu } from "../components/communication-action-menu/communication-action-menu";
import { NavDivider } from "../components/nav-divider/nav-divider";
import { PrimariaNavItem } from "../shared-components/primaria-nav-item/primaria-nav-item";
import { PrimariaNavTreeMenu } from "../shared-components/primaria-nav-tree-menu/primaria-nav-tree-menu";

export type MenuItemConfig =
  | {
      id: string;
      sortHint?: string;
      icon: string;
      label: string;
      type: "item";
      callbackFn: () => void | Promise<void>;
    }
  | {
      id: string;
      sortHint?: string;
      icon: string;
      label: string;
      type: "tree";
      actionMenuItems: {
        icon: string;
        label: string;
        callbackFn?: () => void | Promise<void>;
        hasNestedMenu?: boolean;
        nestedMenuItems?: {
          icon: string;
          label: string;
          callbackFn: () => void | Promise<void>;
        }[];
      }[];
    };

export const commonNavMenuItems = [
  {
    id: "landing",
    icon: "door_front",
    label: "Sortir de l’usuari",
    type: "item",
    sortHint: "0010",
    callbackFn: () => shellApi.broker.send(new ExitShell("OBRIR_PI")),
  },
];

export const registerNavMenuViews = (views: MenuItemConfig[]) => {
  const finalViews = [...commonNavMenuItems, ...views] as MenuItemConfig[];
  for (const item of finalViews) {
    shellApi.regionManager.registerView(shellApi.regionManager.regions.shell.navigationMenu, {
      id: item.id,
      sortHint: item.sortHint,
      factory: () => {
        const menuItem =
          item.type === "item"
            ? new PrimariaNavItem({
                icon: item.icon,
                label: item.label,
                callbackFn: item.callbackFn,
              })
            : new PrimariaNavTreeMenu({
                icon: item.icon,
                label: item.label,
                actionMenuItems: (item as any).actionMenuItems,
              });

        return Promise.resolve(menuItem as any);
      },
    });
  }
};

export const registerCommunicationNavMenu = () => {
  shellApi.regionManager.registerView(shellApi.regionManager.regions.shell.navigationMenu, {
    id: "communication",
    sortHint: "0120",
    factory: () => {
      const menuItem = new CommunicationActionMenu("3p", "Comunicació");

      return Promise.resolve(menuItem as any);
    },
  });
};

export const registerNavMenuDivider = () => {
  shellApi.regionManager.registerView(shellApi.regionManager.regions.shell.navigationMenu, {
    id: "nav-divider",
    sortHint: "0020",
    factory: () => {
      const divider = new NavDivider();
      return Promise.resolve(divider);
    },
  });
};
