import { Component, Inject, PLATFORM_ID } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { SidebarService } from '../../../services/sidebar.service';
import { StorageService } from '../../services/storage.service';
import { CommonModule, isPlatformBrowser } from '@angular/common';
import { TranslateModule } from '@ngx-translate/core';
import { RouterModule } from '@angular/router';
import { Router } from '@angular/router';
import { CredentialService } from '../../../services/credential.service';
import { AuthenticationService } from '../../../services/authenticate.service';

@Component({
  selector: 'app-side-nav',
  imports: [TranslateModule, RouterModule, CommonModule],
  templateUrl: './side-nav.component.html',
  styleUrl: './side-nav.component.scss',
})
export class SideNavComponent {
  isDropdownVisible = false;
  isNotificationsVisible = false;
  searchForm!: FormGroup;
  permissions: any = {};
  activeMenu: string | null = null;
  direction: string = 'ltr';
  constructor(
    private sidebarService: SidebarService,
    @Inject(PLATFORM_ID) private platformId: Object,
    private storageService: StorageService,
    private router: Router,
    private credentialService: CredentialService,
    public authService: AuthenticationService
  ) {
    }

  ngOnInit(): void {
    this.credentialService.getPermission().forEach((permission: any) => {
      this.permissions[permission.name] = permission.checked;
      if(permission.children.length>0){
        permission.children.forEach((child: any)=>{
          this.permissions[child.name] = child.checked;
        })
      }
    });


    this.sidebarService.currentSubModule = this.storageService.getItem('currentSubModule') ?? 'dashboard';
    this.closeSidebarMenu();
  }

  closeSidebarMenu(): void {
    if (isPlatformBrowser(this.platformId)) {
      const subMenus = document.querySelectorAll('#sidebar-menu .sub-menu');
      subMenus.forEach(menu => {
        (menu as HTMLElement).style.display = 'none';
        menu.setAttribute('aria-expanded', 'false');
      });
    }
  }

  toggleMenu(event: Event): void {
    const target = event.currentTarget as HTMLElement;
    const submenu = target.nextElementSibling as HTMLElement;

    if (submenu && submenu.classList.contains('sub-menu')) {
      const isExpanded = submenu.getAttribute('aria-expanded') === 'true';
      submenu.style.display = isExpanded ? 'none' : '';
      submenu.setAttribute('aria-expanded', isExpanded ? 'false' : 'true');
      this.storageService.setItem('menuState' + submenu.id, isExpanded ? 'false' : 'true'); // Saving state per submenu

      if (window.innerWidth <= 992) {
        const links = submenu.querySelectorAll('a');
        links.forEach(link => {
          link.addEventListener('click', () => {
            const body = document.body;
            body.classList.remove('sidebar-enable'); // Hide the sidebar
            this.storageService.setItem('sidebarState', 'collapsed'); // Store collapsed state
          });
        });
      }
    }
  }

  toggleDropdown(): void {
    this.isDropdownVisible = !this.isDropdownVisible;
    this.isNotificationsVisible = false;
  }
  toggleNotifications(): void {
    this.isNotificationsVisible = !this.isNotificationsVisible;
    this.isDropdownVisible = false;
  }
  handleMenuClick(event: Event) {
    const target = event.target as HTMLElement;
    const linkElement = target.closest('a[routerLink]');
    if (linkElement) {
      const routerLink = linkElement.getAttribute('routerLink');
      if (routerLink) {
        this.onModuleClick(routerLink);
      }
    }
  }

  onModuleClick(route: string) {
    const routeParts = route.split('/').filter(part => part.length > 0);
    const lastRoutePart = routeParts[routeParts.length - 1];
    this.sidebarService.currentSubModule = lastRoutePart;
    if (isPlatformBrowser(this.platformId)) {
      this.storageService.setItem('currentSubModule', lastRoutePart);
    }
  }
  
}
