import {
  Component,
  EventEmitter,
  Input,
  OnDestroy,
  OnInit,
  Output,
  ViewChild,
} from "@angular/core";
import { CommonModule } from "@angular/common";
import { menu } from "../../dashboard-menu";
import { RouterModule } from "@angular/router";
import { NgbOffcanvas, NgbOffcanvasModule } from "@ng-bootstrap/ng-bootstrap";
import { Subscription } from "rxjs";
import { SidenavService } from "./sidenav.service";
import { AuthService } from "src/app/cores/services/auth.service";

@Component({
  selector: "dashboard-sidenav",
  standalone: true,
  imports: [CommonModule, RouterModule, NgbOffcanvasModule],
  templateUrl: "./sidenav.component.html",
  styleUrls: ["./sidenav.component.scss"],
})
export class SidenavComponent implements OnInit, OnDestroy {
  @Input() isMobile = false;
  @Output() toggleSidebar = new EventEmitter();
  menu = menu;
  isSidenavCollapsed = false;
  private _isPNGL: boolean | null = null;

  @ViewChild("sidemenuContent") offcanvasContent!: HTMLElement;
  private offcanvasSubscription = new Subscription();

  constructor(
    private sidenav: SidenavService,
    private offcanvas: NgbOffcanvas,
    private auth: AuthService
  ) {}

  ngOnInit(): void {
    this.offcanvasSubscription = this.sidenav
      .getTriggerObservable()
      .subscribe(() => {
        this.offcanvas.open(this.offcanvasContent, {
          ariaLabelledBy: "offcanvas-sidemenu",
        });
      });
  }

  ngOnDestroy(): void {
    this.offcanvasSubscription.unsubscribe();
  }

  onToggleSidebar(): void {
    this.isSidenavCollapsed = !this.isSidenavCollapsed;
    this.toggleSidebar.emit(this.isSidenavCollapsed);
  }

  isPNGL(): boolean {
    if (this._isPNGL !== null) {
      return this._isPNGL;
    }

    const decodedToken = this.auth.getLoggedUser();
    if (decodedToken) {
      const userRole = decodedToken.role.code;
      this._isPNGL = userRole === "SADM";
      return this._isPNGL;
    } else {
      this._isPNGL = false;
      return false;
    }
  }

  isAllowedNameMenu(menuItem: any) {
    const userRole = this.auth.getLoggedUser().role.code;
    return menuItem.access.includes(userRole);
  }
}
