import { ChangeDetectorRef, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { MenuItem } from 'primeng/api';
import { ActiveSidebarService } from 'src/app/core/services/active-sidebar.service';
import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout';
import { Subject, takeUntil } from 'rxjs';
import { BreakpointsService } from 'src/app/core/services/breakpoints.services';
import { API } from 'src/app/core/services/api.service';
import { securityFunctions } from 'src/app/core/common/security';
import { CommonFunctionService } from 'src/app/core/common/common-function.service';
@Component({
  templateUrl: './sidebar.component.html',
  selector: 'side-bar',
})
export class SideBarComponent implements OnInit {
  @ViewChild('logoImage') logoImage: ElementRef<HTMLImageElement>;

  router: any;
  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,
  ) {
    // mobile resposive start
    this.MobileBreakpoints.IsMobile.subscribe({
      next: (val) => {
        this.isMobile = val;
      },
    });
    // mobile resposive end
  }

  asideItems!: MenuItem[];
  ngOnInit(): void {

    // this.asideItems = [
    //   {
    //     label: 'Bookings',
    //     icon: 'pi pi-pw pi-file',
    //     items: [
    //       {
    //         label: 'Search Hotel Booking',
    //         icon: 'pi',
    //         routerLink: '/BookingManagement/HotelBooking/Search',
    //       },
    //       {
    //         label: 'Search Experience Booking',
    //         icon: 'pi',
    //         routerLink: '/BookingManagement/ExperienceBooking/Search',
    //       },
    //     ],
    //   },
    //   {
    //     label: 'Services',
    //     icon: 'pi pi-fw pi-th-large',
    //     items: [
    //       {
    //         label: 'Hotels',
    //         icon: 'pi ',
    //         routerLink: '/Services/HotelServices/Search',
    //       },
    //       {
    //         label: 'Activity',
    //         icon: 'pi ',
    //         items: [
    //           {
    //             label: 'Experience',
    //             icon: 'pi ',
    //             routerLink: '/Services/ActivityServices/ExpServices/Search',
    //           },
    //           {
    //             label: 'Hotel Zone',
    //             icon: 'pi ',
    //             routerLink: '/Services/ActivityServices/HotelZone/Search',
    //           },
    //         ],
    //       },
    //       {
    //         label: 'Flights',
    //         icon: 'pi ',
    //         routerLink: '/Services/FlightServices/Search',
    //       },
    //       {
    //         label: 'Flight Inventory',
    //         icon: 'pi ',
    //         routerLink: '/Services/FlightInventory/Search',
    //       },
    //       {
    //         label: 'Flight Inventory Report',
    //         icon: 'pi ',
    //         routerLink: 'Services/FlightInventoryReport/Search',
    //       },
    //     ],
    //   },
    //   {
    //     label: 'User Configuration',
    //     icon: 'pi pi-fw pi-users',
    //     items: [
    //       {
    //         label: 'Role Management',
    //         icon: 'pi ',
    //         routerLink: '/UserConfiguration/RoleManagement/Search',
    //       },
    //       {
    //         label: 'User Management',
    //         icon: 'pi ',
    //         routerLink: '/UserConfiguration/UserManagement/Search',
    //       },
    //     ],
    //   },
    // ];
    this.isMobile == true
      ? (this.ChcekSidebar.activeSide = '')
      : (this.ChcekSidebar.activeSide = 'IsActive');
    this.getMenus().subscribe(res => {
      if (res) {
        this.commonF.CheckActiveTabMenus(res);
        this.BindMenu(res);
      }
    })
    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' : 'pi pi-fw ' + e.ng_icon,
          items: []
        });
      } else if(!e.is_hide_in_side_menu){
        aisemenu.push({ label: e.menu_name, icon: ' ', 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: ' ', 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
    });
}
}
