import {
  Component,
  inject,
  OnInit,
  TemplateRef,
  ViewChild,
  OnDestroy,
} from '@angular/core'
import { MenuItemType } from '@/app/types/layout'
import { CommonModule } from '@angular/common'
import { NgIcon } from '@ng-icons/core'
import { NgbCollapse } from '@ng-bootstrap/ng-bootstrap'
import { NavigationEnd, Router, RouterLink } from '@angular/router'
import { filter, Subscription } from 'rxjs'
import { scrollToElement } from '@/app/utils/layout-utils'
import { LayoutStoreService } from '@core/services/layout-store.service'
import { MenuService } from '@core/services/menu.service'

@Component({
  selector: 'app-menu',
  imports: [NgIcon, NgbCollapse, RouterLink, CommonModule],
  templateUrl: './app-menu.component.html',
})
export class AppMenuComponent implements OnInit, OnDestroy {
  private router = inject(Router)
  private layout = inject(LayoutStoreService)
  private menuService = inject(MenuService)

  @ViewChild('MenuItemWithChildren', { static: true })
  menuItemWithChildren!: TemplateRef<{ item: MenuItemType }>

  @ViewChild('MenuItem', { static: true })
  menuItem!: TemplateRef<{ item: MenuItemType }>

  menuItems: MenuItemType[] = []
  private subscription?: Subscription

  ngOnInit(): void {
    this.loadFilteredMenu()

    this.router.events
      .pipe(filter((event) => event instanceof NavigationEnd))
      .subscribe(() => {
        this.expandActivePaths(this.menuItems)
        setTimeout(() => this.scrollToActiveLink(), 50)
      })

    setTimeout(() => {
      this.expandActivePaths(this.menuItems)
      this.scrollToActiveLink()
    }, 100)
  }

  ngOnDestroy(): void {
    this.subscription?.unsubscribe()
  }

  private loadFilteredMenu(): void {
    this.menuItems = this.menuService.getMenuItems()
  }

  hasSubMenu(item: MenuItemType): boolean {
    return !!item.children && item.children.length > 0
  }

  expandActivePaths(items: MenuItemType[]): void {
    for (const item of items) {
      if (this.hasSubMenu(item)) {
        item.isCollapsed = !this.isChildActive(item)
        this.expandActivePaths(item.children || [])
      }
    }
  }

  isChildActive(item: MenuItemType): boolean {
    if (item.url && this.router.url === item.url) return true
    if (!item.children) return false
    return item.children.some((child: MenuItemType) =>
      this.isChildActive(child)
    )
  }

  isActive(item: MenuItemType): boolean {
    return this.router.url === item.url
  }

  scrollToActiveLink(): void {
    const activeItem = document.querySelector(
      '[data-active-link="true"]'
    ) as HTMLElement
    const scrollContainer = document.querySelector(
      '#sidenav .simplebar-content-wrapper'
    ) as HTMLElement

    if (activeItem && scrollContainer) {
      const containerRect = scrollContainer.getBoundingClientRect()
      const itemRect = activeItem.getBoundingClientRect()

      const offset = itemRect.top - containerRect.top - window.innerHeight * 0.4

      scrollToElement(scrollContainer, scrollContainer.scrollTop + offset, 500)
    }
  }

  /**
   * Vérifie si un élément de menu doit être affiché selon les permissions
   */
  shouldDisplayItem(item: MenuItemType): boolean {
    // Les titres sont toujours affichés
    if (item.isTitle) return true
    
    // Les éléments sans URL sont affichés (comme les conteneurs)
    if (!item.url || item.url === '#') return true
    
    // Pour les éléments avec URL, vérifier les permissions
    const modulePath = item.url.startsWith('/') ? item.url.substring(1) : item.url
    return this.menuService.canAccess(modulePath)
  }
}