import { Component, inject, OnInit, OnDestroy } from '@angular/core'
import { AuthService } from '@core/services/auth.service'
import { MenuService } from '@core/services/menu.service'
import {
  NgbDropdown,
  NgbDropdownMenu,
  NgbDropdownToggle,
} from '@ng-bootstrap/ng-bootstrap'
import { RouterLink } from '@angular/router'
import { NgIcon } from '@ng-icons/core'
import { UserDropdownItemType } from '@/app/types/layout'
import { Subscription } from 'rxjs'

@Component({
  selector: 'app-user-profile-topbar',
  imports: [
    NgbDropdown,
    NgbDropdownMenu,
    NgbDropdownToggle,
    RouterLink,
    NgIcon,
  ],
  templateUrl: './user-profile.html',
})
export class UserProfile implements OnInit, OnDestroy {
  private authService = inject(AuthService)
  private menuService = inject(MenuService)
  private subscription?: Subscription
  
  menuItems: UserDropdownItemType[] = []

  ngOnInit() {
    this.loadDropdownItems()
    
    // Optionnel : réagir aux changements d'authentification
    this.subscription = this.authService.onAuthState().subscribe(() => {
      this.loadDropdownItems()
    })
  }

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

  private loadDropdownItems() {
    this.menuItems = this.menuService.getUserDropdownItems()
  }

  logout() {
    this.authService.logout()
  }

  handleItemClick(item: UserDropdownItemType) {
    if (item.label === 'Log Out') {
      this.logout()
    }
  }
}