import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { jwtDecode } from 'jwt-decode';
import { ChangePasswordModalComponent } from '../../components/admin/users/users/change-password-modal/change-password-modal.component';
import { MatDialog } from "@angular/material/dialog";
import { GlobalStatusComponent } from 'src/app/components/global-status/global-status.component';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css'],
})

export class HeaderComponent implements OnInit {
  isSuperAdmin: boolean = false;

  @Output() toggleSidebar = new EventEmitter<void>();
  private decodedToken: any;
  private username: any;

  onToggleSidebar() {
    this.toggleSidebar.emit();
  }

  constructor(public dialog: MatDialog) { }

  ngOnInit(): void {
    const token = localStorage.getItem('loginToken');
    if (token) {
      try {
        this.decodedToken = jwtDecode(token);
        this.isSuperAdmin = this.decodedToken.roles.includes('ROLE_SUPER_ADMIN');
        localStorage.setItem('isSuperAdmin', String(this.isSuperAdmin));
        this.username = this.decodedToken.username;
      } catch (error) {
        console.error('Error decoding JWT:', error);
      }
    }
  }

  ngDoCheck(): void {
    this.isSuperAdmin = localStorage.getItem('isSuperAdmin') === 'true';
  }

  editUser() {
    const dialogRef = this.dialog.open(ChangePasswordModalComponent, {
      data: { user: this.decodedToken.username, uuid: this.decodedToken.uuid },
      width: '400px',
    });
  }

  showGlobalStatus() {
    this.dialog.open(GlobalStatusComponent, {
      width: '45vw',
      height: '80vh', 
      // maxWidth: '60vw', 
      // maxHeight: '60vh'
    })
  }
}
