import { ChangeDetectorRef, Component, ElementRef, Renderer2, ViewChild } from '@angular/core';
import { CommonFunctionService } from 'src/app/core/common/common-function.service';
import { ActiveSidebarService } from 'src/app/core/services/active-sidebar.service';
import { API } from 'src/app/core/services/api.service';
import { BreakpointsService } from 'src/app/core/services/breakpoints.services';
import { MenuItem } from 'primeng/api';
import { securityFunctions } from 'src/app/core/common/security';
import { trigger, state, style, transition, animate } from '@angular/animations';
import { filter } from 'rxjs';
import { NavigationEnd, Router } from '@angular/router';

@Component({
  selector: 'custom-sidebar',
  templateUrl: './custom-sidebar.component.html',
  animations: [
    trigger('submenuAnimation', [
      state('closed', style({
        height: '0px',
        opacity: 0,
        overflow: 'hidden',
      })),
      state('open', style({
        height: '*',
        opacity: 1,
        overflow: 'hidden',
      })),
      transition('closed => open', [
        animate('300ms ease-in-out')
      ]),
      transition('open => closed', [
        animate('200ms ease-in-out')
      ])
    ])
  ]
})
export class CustomSidebarComponent {
  @ViewChild('logoImage') logoImage: ElementRef<HTMLImageElement>;
  flag: boolean = true;
  // mobile resposive start
  isMobile = false;
  // mobile resposive end
  constructor(
    public ChcekSidebar: ActiveSidebarService,
    public MobileBreakpoints: BreakpointsService,
    private cd: ChangeDetectorRef, // mobile resposive end,
    private ApiSer: API,
    public commonF: CommonFunctionService,
    private renderer: Renderer2,
    public router: Router
  ) {
    // mobile resposive start
    this.MobileBreakpoints.IsMobile.subscribe({
      next: (val) => {
        this.isMobile = val;
      },
    });
    // mobile resposive end
  }

  asideItems!: MenuItem[];
  ngOnInit(): void {
    this.isMobile == true
      ? (this.ChcekSidebar.activeSide = '')
      : (this.ChcekSidebar.activeSide = 'IsActive');
    this.getMenus().subscribe(res => {
      if (res) {
        this.commonF.CheckActiveTabMenus(res);
        this.BindMenu(res);
        const currentUrl = this.router.url;
        this.expandAndActivateRecursive(this.asideItems, currentUrl, true);
      }
    })
    this.router.events
      .pipe(filter(event => event instanceof NavigationEnd))  // Filter to get NavigationEnd event
      .subscribe((data) => {
        this.resetMenuItems(this.asideItems);
        // this.expandAndActivateRecursive(this.asideItems, this.router.url, true);
      });
    this.cd.detectChanges();

  }
  getMenuss() {
    let LoginUserData = securityFunctions.getSessionStorage('LoginUserData') ? JSON.parse(securityFunctions.getSessionStorage('LoginUserData')) : null;
    return this.ApiSer.AdminGet(`/MenuMasterNew/GetMenuMasterNewsByOrgId/2405170833594899108/${LoginUserData.user_id}`)
  }
  getMenus() {
    let LoginUserData = securityFunctions.getSessionStorage('LoginUserData') ? JSON.parse(securityFunctions.getSessionStorage('LoginUserData')) : null;
    return this.ApiSer.AdminGet('/MenuMasterNew/GetAllMenuByUserId/' + LoginUserData.user_id + '/2405170833594899108')
  }
  BindMenu(list) {
    let aisemenu = [];
    let FliterList = list.sort(function (a, b) { return a.sequence - b.sequence; });
    let AllParentlist = list.filter(e => e.parent_id == '');
    AllParentlist.forEach(e => {
      if (e.menu_type == '2305170833594899101' && !e.is_tab_wise_menu) {
        aisemenu.push({
          label: e.menu_name,
          icon: e.ng_icon == null ? 'pi pi-fw pi-pencil' : '' + e.ng_icon,
          items: []
        });
      } else if (!e.is_hide_in_side_menu) {
        aisemenu.push({ label: e.menu_name, icon: ' ', page_data: e.page_data ? JSON.parse(e.page_data) : [], routerLink: '/' + e.ui_controller + '/' + e.ui_action, command: (event) => { this.isMobile ? this.ChcekSidebar.SideBar('IsActive') : '' } });
      }
      let index = aisemenu.length - 1;
      let submenu = FliterList.filter(s => s.parent_id == e.menu_id);
      if (submenu.length > 0) {
        this.subMenu(aisemenu[index], submenu, FliterList);
      }
    });
    this.asideItems = aisemenu;
  };

  subMenu(menu, FilterSubmenu, Allmenu) {
    if (FilterSubmenu.length > 0) {
      FilterSubmenu.forEach(e => {
        if (e.menu_type == '2305170833594899101' && !e.is_tab_wise_menu) {
          menu.items.push({
            label: e.menu_name,
            icon: 'pi pi-fw pi-pencil',
            items: []
          });
        } else if (!e.is_hide_in_side_menu) {
          menu.items.push(
            { label: e.menu_name, icon: ' ', page_data: e.page_data ? JSON.parse(e.page_data) : [], routerLink: '/' + e.ui_controller + '/' + e.ui_action, command: (event) => { this.isMobile ? this.ChcekSidebar.SideBar('IsActive') : '' } }
          );
        }
        let index = menu.items.length - 1;
        let submenu = Allmenu.filter(a => a.parent_id == e.menu_id && !e.is_tab_wise_menu);
        if (submenu.length > 0) {
          this.subMenu(menu.items[index], submenu, Allmenu);
        }
      });
    };
  };
  headerHeight; // Default height
  isHeightSet: boolean = false; // Flag to check if actual height is set
  adjustHeaderSize() {
    requestAnimationFrame(() => {
      this.headerHeight = this.commonF.getHeaderSize(this.logoImage);
      if (this.headerHeight > 0) { // Check if the height is valid
        this.isHeightSet = true;
      }
      this.cd.detectChanges(); // Trigger change detection
    });
  }

  toggleSubMenu(selectedItem: any) {
    this.asideItems.forEach(item => item.expanded = item.label === selectedItem.label ? !item.expanded : false);
  }

  private expandAndActivateRecursive(items: MenuItem[], targetUrl: string, isBeforeActive: boolean = true): boolean {
    let menu = true;
    if (items) {
      for (const [i, item] of items.entries()) {
        if (item.routerLink) {
          if (item['page_data'].some(z => targetUrl.includes(z.page_url.replaceAll('/$', '')))) {
            item.expanded = true;
            item.styleClass = 'SidebarMenulink';
            menu = false;
            for (let ind = i + 1; ind < items.length; ind++) {
              if (items[ind].items) {
                items[ind].items.forEach(sub_item => sub_item.styleClass = '')
              }
            }
            return true;
          }
        } else if (item.items) {
          if (this.expandAndActivateRecursive(item.items, targetUrl, isBeforeActive)) {
            item.expanded = true;
            item.styleClass = 'parent-menu-active';
            for (let ind = i + 1; ind < items.length; ind++) {
              if (items[ind].items) {
                items[ind].items.forEach(sub_item => sub_item.styleClass = '')
              }
            }
            // this.RemoveSubmenuActive(items,index+1);
            return true;
          } else {
            item.styleClass = '';
          }
        }
        if (menu) {
          item.styleClass = 'submenu-before-active';
        }
      }
    }
    // Get the active panel (the expanded one)
    const activePanel = document.querySelector('.menu');
    const selected_panel = activePanel.querySelector('.active-panel')
    selected_panel?.classList.remove("active-panel")
    const panel = activePanel.querySelector('.p-highlight')?.closest('.p-panelmenu-panel');

    // Add 'active-panel' class to the currently active panel
    if (panel) {
      this.renderer.addClass(panel, 'active-panel');
    }
    return false;
  }
  private resetMenuItems(items: MenuItem[]) {
    if (items) {
      for (const [index, item] of items.entries()) {
        item.expanded = false;
        item.expanded = false;  // Reset expanded state
        item.styleClass = '';   // Clear any existing style classes
        if (item.items) {
          this.resetMenuItems(item.items); // Recursively reset child items
        }
      }
      this.expandAndActivateRecursive(items, this.router.url, true)
    }
  }
}
