import { Component, DOCUMENT, ElementRef, Renderer2, inject } from '@angular/core';
import { Menu, NavService } from '../../services/nav.service';
import * as headeData from "./headerdata"
import { AppStateService } from '../../services/app-state.service';
import { Subscription } from 'rxjs';
import { Router, RouterLink } from '@angular/router';
import { FullscreenDirective } from '../../directives/fullscreen.directive';
import { FormsModule } from '@angular/forms';
import { SlicePipe } from '@angular/common';
import { AuthService } from '../../../core/auth/auth.service';
interface Item {
  id: number;
  name: string;
  type: string;
  title: string;
  // Add other properties as needed
}
declare const HSStaticMethods: any;
@Component({
    selector: 'app-header',
    templateUrl: './header.html',
    styleUrls: ['./header.scss'],
    imports: [RouterLink, FullscreenDirective, FormsModule, SlicePipe]
})

export class Header {
  headeData = headeData;
  public menuItems!: Menu[];
  public menuitemsSubscribe$!: Subscription;
  public NavServices = inject(NavService)
  private appStateService = inject(AppStateService)
  private readonly authService = inject(AuthService);
  private readonly router = inject(Router);
  readonly currentUser = this.authService.currentUserSignal;
  Selector = (selector: any) => document.querySelector(selector);

  SelectorAll = (selector: any) => document.querySelectorAll(selector);

  private doc = inject(DOCUMENT);
  toggleSidebar() {
    const html = this.doc.documentElement;
    // Check the window width
    if (window.innerWidth <= 992) {
      let dataToggled = html.getAttribute("data-toggled");

      if (dataToggled == "open") {
        html.setAttribute("data-toggled", "close");
      } else {
        html.setAttribute("data-toggled", "open");
      }
    }
    else {
      let menuNavLayoutType = html.getAttribute("data-nav-style");
      let verticalStyleType = html.getAttribute("data-vertical-style");

      if (menuNavLayoutType) {
        let dataToggled = html.getAttribute("data-toggled");
        if (dataToggled) {
          html.removeAttribute("data-toggled");
        } else {
          html.setAttribute(
            "data-toggled",
            menuNavLayoutType + "-closed",
          );
        }
      } else if (verticalStyleType) {
        let dataToggled = html.getAttribute("data-toggled");

        if (verticalStyleType == "doublemenu") {
          if (
            html.getAttribute("data-toggled") === "double-menu-open" && this.Selector(".double-menu-active")) {
            html.setAttribute("data-toggled", "double-menu-close");
          } else {
            if (this.Selector(".double-menu-active")) { html.setAttribute("data-toggled", "double-menu-open"); }
          }
        } else if (dataToggled) {
          html.removeAttribute("data-toggled");
        } else {
          switch (verticalStyleType) {
            case "closed":
              html.setAttribute(
                "data-toggled",
                "close-menu-close",
              );
              break;
            case "icontext":
              html.setAttribute(
                "data-toggled",
                "icon-text-close",
              );
              break;
            case "overlay":
              html.setAttribute(
                "data-toggled",
                "icon-overlay-close",
              );
              break;
            case "detached":
              html.setAttribute("data-toggled", "detached-close");
              break;
            default:
          }
        }
      }
    }
  }


  public items: Menu[] = []; // Your full menu data (source)
  public text: string = '';
  public SearchResultEmpty: boolean = false;
  public isDropdownVisible: boolean = false;
  Search(searchText: string) {
    // 2. Safety Check: If search is empty or source data hasn't loaded
    if (!searchText || !this.items) {
      this.menuItems = [];
      this.SearchResultEmpty = false;
      return;
    }

    const results: Menu[] = [];
    const query = searchText.toLowerCase().trim();

    // 3. Deep search through 3 levels of menu
    this.items.forEach((level1: Menu) => {
      // Check Level 1
      if (level1.title?.toLowerCase().includes(query)) {
        results.push(level1);
      }

      // Check Level 2 (Children)
      if (level1.children) {
        level1.children.forEach((level2: Menu) => {
          if (level2.title?.toLowerCase().includes(query)) {
            results.push(level2);
          }

          // Check Level 3 (Sub-children)
          if (level2.children) {
            level2.children.forEach((level3: Menu) => {
              if (level3.title?.toLowerCase().includes(query)) {
                results.push(level3);
              }
            });
          }
        });
      }
    });

    // 4. Update UI State
    this.menuItems = results;
    this.SearchResultEmpty = results.length === 0;
  }



  //  Used to clear previous search result
  clearSearch() {
    const headerSearch = this.Selector('.header-search');
    if (headerSearch) {
      headerSearch.classList.remove('searchdrop');
    }
    this.text = '';
    this.menuItems = [];
    this.SearchResultEmpty = false;
    return this.text, this.menuItems;

  }

  updateTheme(theme: string) {


    this.appStateService.updateState({ theme, menuColor: theme, headerColor: theme });
    if (theme == 'light') {
      this.appStateService.updateState({ theme, themeBackground: '', headerColor: 'light', menuColor: 'dark' });
      let html = document.querySelector('html');
      html?.style.removeProperty('--color-bodybg');
      html?.style.removeProperty('--color-bodybg2');
      html?.style.removeProperty('--color-light');
      html?.style.removeProperty('--color-formcontrolbg');
      html?.style.removeProperty('--color-inputborder');
      html?.style.removeProperty('--color-gray3');
      if (window.innerWidth <= 992) {
        html?.setAttribute('data-toggled', 'close');
      }
    }
    if (theme == 'dark') {
      this.appStateService.updateState({ theme, themeBackground: '', headerColor: 'dark', menuColor: 'dark' });
      let html = document.querySelector('html');
      html?.style.removeProperty('--color-bodybg');
      html?.style.removeProperty('--color-bodybg2');
      html?.style.removeProperty('--color-light');
      html?.style.removeProperty('--color-formcontrolbg');
      html?.style.removeProperty('--color-inputborder');
      html?.style.removeProperty('--color-gray3');
      if (window.innerWidth <= 992) {
        html?.setAttribute('data-toggled', 'close');
      }
    }
  }


  cartItemCount = this.headeData.cartItems.length;
  notificationItemCount = this.headeData.notifications.length;
  handleCardClick(event: MouseEvent) {
    // Prevent the click event from propagating to the container
    event.stopPropagation();
  }
  removeRow(itemId: string,event: MouseEvent) {
    const index = this.headeData.cartItems.findIndex(i => i.id === itemId);
    if (index !== -1) {
      this.headeData.cartItems.splice(index, 1);
    }
    this.updateCartItemCount();
      event.stopPropagation();
  }
  updateCartItemCount() {
    this.cartItemCount = this.headeData.cartItems.length;
  }

  removeNotification(id: number, event: Event): void {
    event.preventDefault(); // Prevent link navigation
    this.headeData.notifications.splice(
      this.headeData.notifications.findIndex(item => item.id === id),
      1
    );

    this.updatenotificationsItemCount();
  }

  updatenotificationsItemCount() {
    this.notificationItemCount = this.headeData.notifications.length;
  }

  isFullscreen: boolean = false;
  toggleFullscreen() {

    this.isFullscreen = !this.isFullscreen;
  }



  removeAlert<T extends { id: string }>(array: T[], id: string): void {
    const index = array.findIndex(item => item.id === id);

    if (index !== -1) {
      array.splice(index, 1);
    }
  }

  ngOnInit(): void {
    this.NavServices.items.subscribe((menuItems) => {
      this.items = menuItems;
    });
  }

  ngAfterViewInit(): void {
    HSStaticMethods.autoInit();
  }

  getDisplayName(): string {
    const email = this.currentUser()?.email?.trim();
    if (email) {
      const localPart = email.split('@')[0];
      const formatted = localPart
        .replace(/[._-]+/g, ' ')
        .replace(/\s+/g, ' ')
        .trim();

      if (formatted) {
        return formatted
          .split(' ')
          .filter(Boolean)
          .map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
          .join(' ');
      }
    }

    return this.currentUser()?.displayName?.trim() || 'User';
  }

  getPrimaryRole(): string {
    const roles = this.currentUser()?.roles;
    if (roles && roles.length > 0) {
      const role = roles[0].trim();
      if (role) {
        return role
          .replace(/[_-]+/g, ' ')
          .replace(/\s+/g, ' ')
          .split(' ')
          .filter(Boolean)
          .map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
          .join(' ');
      }
    }

    return 'User';
  }

  handleProfileItemClick(item: { label?: string; link?: string | null }, event: MouseEvent): void {
    event.preventDefault();

    if (item.label === 'Log Out') {
      this.logout();
      return;
    }

    if (item.link) {
      void this.router.navigateByUrl(item.link);
    }
  }

  logout(): void {
    this.authService.logout();
    void this.router.navigate(['/auth/login']);
  }
}

