import type { ModuleKey } from "@platform-types";

export type TenantPermission =
  | "assistant"
  | "ordini"
  | "prenotazioni"
  | "documents"
  | "menu"
  | "homemade"
  | "fiscal_documents"
  | "timeclock"
  | "inventory";

export type WorkspaceLink = {
  id: string;
  label: string;
  mobileLabel: string;
  description: string;
} & (
  | {
      kind: "internal";
      to: string;
    }
  | {
      kind: "module";
      moduleKey: ModuleKey;
    }
);

export type AssistantShortcut = {
  id: string;
  label: string;
  summary: string;
  href: string;
};

export type TenantPermissionOption = {
  key: TenantPermission;
  label: string;
  description: string;
};

const DEFAULT_STAFF_PERMISSIONS: TenantPermission[] = ["prenotazioni", "menu", "homemade"];

export const tenantPermissionOptions: TenantPermissionOption[] = [
  {
    key: "assistant",
    label: "Assistente",
    description: "Chat operativa della Home del locale.",
  },
  {
    key: "prenotazioni",
    label: "Prenotazioni",
    description: "Agenda, tavoli, sala e WhatsApp del locale.",
  },
  {
    key: "menu",
    label: "Menu",
    description: "Assistente menu e materiali del locale.",
  },
  {
    key: "homemade",
    label: "Homemade",
    description: "Ricette e contenuti interni del locale.",
  },
  {
    key: "ordini",
    label: "Ordini",
    description: "Catalogo fornitori, storico e obiettivi.",
  },
  {
    key: "documents",
    label: "Documenti",
    description: "Generazione file e salvataggio su Google Workspace.",
  },
  {
    key: "fiscal_documents",
    label: "Documenti fiscali",
    description: "Fatture, bolle e controlli amministrativi del locale.",
  },
  {
    key: "timeclock",
    label: "Cartellino",
    description: "Timbra inizio e fine turno e consulta ore lavorate del team.",
  },
  {
    key: "inventory",
    label: "Inventario",
    description: "Magazzini del locale, stock disponibile e carichi di merce.",
  },
];

const tenantWorkspaceLinks: WorkspaceLink[] = [
  {
    id: "home",
    to: "/home",
    label: "Assistente",
    mobileLabel: "Home",
    description: "Cervello operativo del locale e prossimo passo.",
    kind: "internal",
  },
  {
    id: "timeclock",
    to: "/timeclock",
    label: "Cartellino",
    mobileLabel: "Cartellino",
    description: "Turni attivi, ore lavorate e storico staff.",
    kind: "internal",
  },
  {
    id: "dashboard",
    to: "/dashboard",
    label: "Strumenti",
    mobileLabel: "Strumenti",
    description: "Tool operativi del locale.",
    kind: "internal",
  },
  {
    id: "inventory",
    to: "/inventory",
    label: "Inventario",
    mobileLabel: "Inventario",
    description: "Magazzini, stock disponibile e merce presente nel locale.",
    kind: "internal",
  },
  {
    id: "ordini",
    moduleKey: "ordini",
    label: "Ordini",
    mobileLabel: "Ordini",
    description: "Catalogo, storico e richieste fornitori.",
    kind: "module",
  },
  {
    id: "prenotazioni",
    moduleKey: "prenotazioni",
    label: "Prenotazioni",
    mobileLabel: "Prenota",
    description: "Agenda, sala e tavoli del locale.",
    kind: "module",
  },
  {
    id: "documents",
    to: "/documents",
    label: "Documenti",
    mobileLabel: "Documenti",
    description: "Brief, preview e salvataggio su Google Workspace.",
    kind: "internal",
  },
  {
    id: "menu",
    moduleKey: "menu",
    label: "Menu",
    mobileLabel: "Menu",
    description: "Concierge menu e carta vini del locale.",
    kind: "module",
  },
  {
    id: "homemade",
    to: "/homemade",
    label: "Homemade",
    mobileLabel: "Homemade",
    description: "Archivio ricette e contenuti interni.",
    kind: "internal",
  },
  {
    id: "account",
    to: "/account",
    label: "Account",
    mobileLabel: "Account",
    description: "Sotto-account del locale e accessi del team.",
    kind: "internal",
  },
];

export const adminWorkspaceLinks: WorkspaceLink[] = [
  {
    id: "admin",
    to: "/admin",
    label: "Admin",
    mobileLabel: "Admin",
    description: "Clienti, account admin e ingresso nei singoli locali.",
    kind: "internal",
  },
];

export const workspaceTitles: Record<string, string> = {
  "/home": "Assistente",
  "/dashboard": "Strumenti",
  "/fiscal-documents": "Documenti fiscali",
  "/documents": "Documenti",
  "/timeclock": "Cartellino",
  "/inventory": "Inventario",
  "/account": "Account",
  "/homemade": "Homemade",
  "/admin": "Console admin",
  "/architecture": "Architettura",
};

function normalizeTenantPermissions(role: string | null | undefined, permissions: string[] | null | undefined): TenantPermission[] {
  if (role === "owner" || role === "super_admin") {
    return tenantPermissionOptions.map((option) => option.key);
  }

  if (permissions == null) {
    return role === "staff" ? [...DEFAULT_STAFF_PERMISSIONS] : [];
  }

  const allowed = new Set(tenantPermissionOptions.map((option) => option.key));
  const normalized = (permissions ?? [])
    .map((item) => item.trim().toLowerCase())
    .filter((item): item is TenantPermission => allowed.has(item as TenantPermission));

  return normalized;
}

export function getDefaultStaffPermissions(): TenantPermission[] {
  return [...DEFAULT_STAFF_PERMISSIONS];
}

export function canManageTenantAccounts(role: string | null | undefined): boolean {
  return role === "owner" || role === "super_admin";
}

export function hasTenantPermission(
  role: string | null | undefined,
  permissions: string[] | null | undefined,
  permission: TenantPermission
): boolean {
  if (role === "owner" || role === "super_admin") {
    return true;
  }
  return normalizeTenantPermissions(role, permissions).includes(permission);
}

function modulePermission(moduleKey: ModuleKey): TenantPermission | null {
  if (moduleKey === "ordini") {
    return "ordini";
  }
  if (moduleKey === "prenotazioni") {
    return "prenotazioni";
  }
  if (moduleKey === "menu") {
    return "menu";
  }
  if (moduleKey === "homemade") {
    return "homemade";
  }
  return null;
}

export function getWorkspaceTitle(pathname: string, isPlatformConsole: boolean): string {
  return workspaceTitles[pathname] ?? (isPlatformConsole ? "Console piattaforma" : "Workspace locale");
}

export function getModuleWorkspaceHref(moduleKey: ModuleKey): string {
  return `/modules/${moduleKey}`;
}

export function canAccessTenantModule(
  role: string | null | undefined,
  permissions: string[] | null | undefined,
  moduleKey: ModuleKey
): boolean {
  const requiredPermission = modulePermission(moduleKey);
  if (!requiredPermission) {
    return role !== "staff";
  }
  return hasTenantPermission(role, permissions, requiredPermission);
}

export function canAccessTenantPath(
  role: string | null | undefined,
  permissions: string[] | null | undefined,
  pathname: string
): boolean {
  if (role !== "staff") {
    return true;
  }

  if (pathname === "/home") {
    return true;
  }

  if (pathname === "/dashboard") {
    return hasTenantPermission(role, permissions, "fiscal_documents");
  }

  if (pathname === "/timeclock") {
    return hasTenantPermission(role, permissions, "timeclock");
  }

  if (pathname === "/inventory") {
    return hasTenantPermission(role, permissions, "inventory");
  }

  if (pathname === "/fiscal-documents") {
    return hasTenantPermission(role, permissions, "fiscal_documents");
  }

  if (pathname === "/documents") {
    return hasTenantPermission(role, permissions, "documents");
  }

  if (pathname === "/homemade") {
    return hasTenantPermission(role, permissions, "homemade");
  }

  if (pathname.startsWith("/modules/")) {
    const moduleKey = pathname.split("/")[2] as ModuleKey | undefined;
    return Boolean(moduleKey && canAccessTenantModule(role, permissions, moduleKey));
  }

  return false;
}

export function getTenantDefaultPath(role: string | null | undefined, permissions?: string[] | null | undefined): string {
  if (role === "staff" && hasTenantPermission(role, permissions, "timeclock")) {
    return "/timeclock";
  }
  return "/home";
}

export function getVisibleTenantWorkspaceLinks(
  role: string | null | undefined,
  permissions: string[] | null | undefined
): WorkspaceLink[] {
  return tenantWorkspaceLinks.filter((link) => {
    if (role === "staff") {
      if (link.id === "home") {
        return true;
      }

      if (link.id === "dashboard") {
        return hasTenantPermission(role, permissions, "fiscal_documents");
      }

      if (link.id === "timeclock") {
        return hasTenantPermission(role, permissions, "timeclock");
      }

      if (link.id === "inventory") {
        return hasTenantPermission(role, permissions, "inventory");
      }

      if (link.id === "documents") {
        return hasTenantPermission(role, permissions, "documents");
      }

      if (link.id === "homemade") {
        return hasTenantPermission(role, permissions, "homemade");
      }

      if (link.id === "account") {
        return true;
      }

      if (link.kind === "module") {
        return canAccessTenantModule(role, permissions, link.moduleKey);
      }

      return false;
    }

    if (link.id === "account") {
      return canManageTenantAccounts(role);
    }

    return true;
  });
}

export function resolveWorkspaceLinkHref(link: WorkspaceLink): string {
  return link.kind === "internal" ? link.to : getModuleWorkspaceHref(link.moduleKey);
}

export function buildAssistantShortcuts(): AssistantShortcut[] {
  return [
    {
      id: "ordini",
      label: "Ordini",
      summary: "Catalogo, fornitori e fabbisogni del servizio.",
      href: getModuleWorkspaceHref("ordini"),
    },
    {
      id: "prenotazioni",
      label: "Prenotazioni",
      summary: "Agenda, tavoli, capienza e disponibilita live.",
      href: getModuleWorkspaceHref("prenotazioni"),
    },
    {
      id: "documents",
      label: "Documenti",
      summary: "Brief, anteprime e salvataggio su Google Workspace.",
      href: "/documents",
    },
    {
      id: "menu",
      label: "Menu",
      summary: "Assistente menu, materiali caricati e focus vendita.",
      href: getModuleWorkspaceHref("menu"),
    },
  ];
}

export function describeTenantAccess(pathname: string, moduleKey?: ModuleKey | null): string {
  if (moduleKey) {
    const moduleLabels: Record<ModuleKey, string> = {
      ordini: "Ordini",
      prenotazioni: "Prenotazioni",
      menu: "Menu",
      homemade: "Homemade",
    };
    return moduleLabels[moduleKey] ?? "questa sezione";
  }

  if (pathname === "/dashboard" || pathname === "/fiscal-documents") {
    return "Strumenti";
  }
  if (pathname === "/timeclock") {
    return "Cartellino";
  }
  if (pathname === "/inventory") {
    return "Inventario";
  }
  if (pathname === "/documents") {
    return "Documenti";
  }
  if (pathname === "/account") {
    return "Account";
  }
  if (pathname === "/architecture") {
    return "questa sezione";
  }
  return getWorkspaceTitle(pathname, false).toLowerCase();
}
