import { Injectable, inject } from '@angular/core';
import { AuthService } from './auth.service';
import { PermissionsService } from './permissions.service';
import { MenuItemType, UserDropdownItemType } from '@/app/types/layout';

@Injectable({ providedIn: 'root' })
export class MenuService {
  private authService = inject(AuthService);
  private permissionsService = inject(PermissionsService);

  getMenuItems(): MenuItemType[] {
    const userRoles = this.authService.getCurrentUserRoles();
    return this.filterMenuItems(this.getFullMenu(), userRoles);
  }

  getUserDropdownItems(): UserDropdownItemType[] {
    const userRoles = this.authService.getCurrentUserRoles();
    return this.filterUserDropdownItems(this.getFullUserDropdown(), userRoles);
  }

  canAccess(modulePath: string): boolean {
    const userRoles = this.authService.getCurrentUserRoles();
    return this.permissionsService.canAccessModule(modulePath, userRoles);
  }

  private filterMenuItems(items: MenuItemType[], userRoles: string[]): MenuItemType[] {
    return items
      .filter(item => this.shouldDisplayMenuItem(item, userRoles))
      .map(item => ({
        ...item,
        children: item.children ? this.filterMenuItems(item.children, userRoles) : undefined
      }));
  }

  private shouldDisplayMenuItem(item: MenuItemType, userRoles: string[]): boolean {
    if (item.isTitle) return true;
    
    if (item.url && item.url !== '#') {
      const modulePath = this.normalizePath(item.url);
      return this.permissionsService.canAccessModule(modulePath, userRoles);
    }

    if (item.children) {
      return this.filterMenuItems(item.children, userRoles).length > 0;
    }

    return true;
  }

  private filterUserDropdownItems(items: UserDropdownItemType[], userRoles: string[]): UserDropdownItemType[] {
    return items.filter(item => {
      if (item.isDivider || item.isHeader || !item.url || item.url === '#') {
        return true;
      }
      const modulePath = this.normalizePath(item.url);
      return this.permissionsService.canAccessModule(modulePath, userRoles);
    });
  }

  private normalizePath(url: string): string {
    return url.startsWith('/') ? url.substring(1) : url;
  }

  private getFullMenu(): MenuItemType[] {
    return [
      { label: 'Pilotage', isTitle: true },
      {
        label: 'Tableau de Bord',
        icon: 'lucideBarChart2',
        url: '/dcb-dashboard',
      },

      { label: 'Business & Transactions', isTitle: true },
      {
        label: 'Transactions DCB',
        icon: 'lucideCreditCard',
        url: '/transactions',
      },
      {
        label: 'Gestions Merchants/Partenaires',
        icon: 'lucideStore',
          url: '/merchant-partners'
      },
      {
        label: 'Opérateurs',
        icon: 'lucideServer',
        isCollapsed: true,
        children: [
          { label: 'Paramètres d\'Intégration', url: '/operators/config' },
          { label: 'Performance & Monitoring', url: '/operators/stats' },
        ],
      },

      {
        label: 'Webhooks',
        icon: 'lucideShare',
        isCollapsed: true,
        children: [
          { label: 'Historique', url: '/webhooks/history' },
          { label: 'Statut des Requêtes', url: '/webhooks/status' },
          { label: 'Relancer Webhook', url: '/webhooks/retry' },
        ],
      },

      { label: 'Utilisateurs & Sécurité', isTitle: true },
      {
        label: 'Gestion des Utilisateurs',
        icon: 'lucideUsers',
        url: '/users',
      },

      { label: 'Configuration', isTitle: true },
      { label: 'Paramètres Système', icon: 'lucideSettings', url: '/settings' },
      { label: 'Intégrations Externes', icon: 'lucidePlug', url: '/integrations' },

      { label: 'Support & Profil', isTitle: true },
      { label: 'Support', icon: 'lucideLifeBuoy', url: '/support' },
      { label: 'Mon Profil', icon: 'lucideUser', url: '/profile' },

      { label: 'Informations', isTitle: true },
      { label: 'Documentation', icon: 'lucideBookOpen', url: '/documentation' },
      { label: 'Aide', icon: 'lucideHelpCircle', url: '/help' },
      { label: 'À propos', icon: 'lucideInfo', url: '/about' },
    ];
  }

  private getFullUserDropdown(): UserDropdownItemType[] {
  return [
    { label: 'Welcome back!', isHeader: true },
    { label: 'Profile', icon: 'tablerUserCircle', url: '/profile' },
    { label: 'Account Settings', icon: 'tablerSettings2', url: '/settings' },
    { label: 'Support Center', icon: 'tablerHeadset', url: '/support' },
    { isDivider: true },
    { 
      label: 'Log Out', 
      icon: 'tablerLogout2', 
      url: '#', 
      class: 'fw-semibold text-danger' 
    },
  ];
}
}