import { Component, HostListener, Inject, OnInit, PLATFORM_ID } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { SidebarService } from '../../../services/sidebar.service';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { StorageService } from '../../services/storage.service';
import { isPlatformBrowser, formatDate, CommonModule } from '@angular/common';
import { AuthenticationService } from '../../../services/authenticate.service';

@Component({
  selector: 'app-header',
  imports: [TranslateModule, CommonModule],
  templateUrl: './header.component.html',
  styleUrl: './header.component.scss'
})
export class HeaderComponent implements OnInit{
  isDropdownVisible: boolean;
  isVacDropdownVisible: boolean;
  isNotificationsVisible: boolean;
  notifications = [
    {
      imgSrc: '',
      title: 'Salena Layfield',
      message: 'As a skeptical Cambridge friend of mine occidental.',
      timeAgo: '1 hour ago'
    },
  ];
  direction: string = 'ltr';
  user: any;
  userObj: any;
  username : string = '';
  mismatchedDates: string = "";
  dateColor = "black";
  date: any;
  vacName: any;
  allVacs: any;
  constructor(
    public sidebarService: SidebarService,
    @Inject(PLATFORM_ID) private platformId: Object,
    private storageService: StorageService,
    public authService: AuthenticationService
  ) {
    this.isDropdownVisible = false;
    this.isVacDropdownVisible = false;
    this.isNotificationsVisible = false;
    this.date = new Date().toISOString().split('T')[0];
  }
  ngOnInit(): void {
    if (typeof document !== 'undefined' && typeof window !== 'undefined') {
      this.initializeVerticalMenuToggle();
      this.initializeFullscreenToggle();
      const body = document.body;
      if (window.innerWidth >= 992) {
        const isCollapsed = body.classList.toggle('sidebar-enable');
        this.storageService.setItem('sidebarState', isCollapsed ? 'expanded' : 'collapsed');
      }
    }
    this.userObj = JSON.parse(this.storageService.getItem('user') || '{}');
    this.username = this.userObj?.user?.userFullname ?? '';
  }

  ngAfterViewInit(): void {

  }

  initializeVerticalMenuToggle(): void {
    if (isPlatformBrowser(this.platformId)) {
      const verticalMenuBtn = document.getElementById('vertical-menu-btn');
      if (window.innerWidth <= 992) {
        const body = document.body;
        body.classList.add('vertical-collpsed');
      }
      if (verticalMenuBtn) {
        verticalMenuBtn.addEventListener('click', this.toggleSidebar.bind(this));
      }
    }
  }
  initializeFullscreenToggle(): void {
    if (isPlatformBrowser(this.platformId)) {
      const fullscreenButton = document.querySelector<HTMLButtonElement>('[data-bs-toggle="fullscreen"]');
      if (fullscreenButton) {
        fullscreenButton.addEventListener("click", () => {
          if (!document.fullscreenElement) {
            this.toggleFullscreen(true);
          } else {
            this.toggleFullscreen(false);
          }
        });
      }
    }
  }

  toggleFullscreen(enter: boolean): void {
    if (isPlatformBrowser(this.platformId)) {
      if (enter) {
        document.documentElement.requestFullscreen();
      } else {
        document.exitFullscreen();
      }
      document.body.classList.toggle('fullscreen-enable', enter);
    }
  }

  toggleSidebar(): void {
    if (isPlatformBrowser(this.platformId)) {
      const body = document.body;
      const isSidebarEnabled = body.classList.toggle('sidebar-enable');
      if (window.innerWidth >= 992) {
        const isCollapsed = body.classList.toggle('vertical-collpsed');
        this.storageService.setItem('sidebarState', isCollapsed ? 'collapsed' : 'expanded');
        if (isCollapsed) {
          const subMenus = document.querySelectorAll('.sub-menu');
          subMenus.forEach(menu => {
            (menu as HTMLElement).style.display = '';
            menu.setAttribute('aria-expanded', 'false');
          });
        } else {
          const subMenus = document.querySelectorAll('.sub-menu');
          subMenus.forEach(menu => {
            (menu as HTMLElement).style.display = 'none';
            menu.setAttribute('aria-expanded', 'false');
          });
        }
      } else {
        body.classList.remove('vertical-collpsed');
        this.storageService.setItem('sidebarState', 'expanded');
        const subMenus = document.querySelectorAll('.sub-menu');
        subMenus.forEach(menu => {
          (menu as HTMLElement).style.display = 'none';
          menu.setAttribute('aria-expanded', 'false');
        });
      }
    }
  }

  toggleDropdown(): void {
    this.isDropdownVisible = !this.isDropdownVisible;
    this.isNotificationsVisible = false;
  }

  toggleVacDropdown(): void {
    this.isVacDropdownVisible = !this.isVacDropdownVisible;
    this.isNotificationsVisible = false;
  }
  toggleNotifications(): void {
    this.isNotificationsVisible = !this.isNotificationsVisible;
    this.isDropdownVisible = false;
  }

  // toggleSidebar() {
  //   this.sidebarService.toggleSidebar();
  // }
  logout() {
    this.authService.logout();
  }
  @HostListener('document:click', ['$event'])
  handleClickOutside(event: MouseEvent) {
    const targetElement = event.target as HTMLElement;
    const isClickInsideProfileDropdown = targetElement.closest('.profile-dropdown');
    const isClickInsideVacDropdown = targetElement.closest('.vac-dropdown');
    if (!isClickInsideProfileDropdown) {
      this.isDropdownVisible = false;
    }
    if (!isClickInsideVacDropdown) {
      this.isVacDropdownVisible = false;
    }
  }



  formatDate(date?: Date) {
    if ((date && !isNaN(date.getTime())) || (date != null || date != undefined)) {
      // Adil 5152 - Changing the Date Locale based on the language selected
      return formatDate(date, 'EEEE, d MMMM yyyy', 'en');
    }
    return null;
  }

}
