import { Component, ElementRef, Input, OnInit, QueryList, SimpleChanges, ViewChildren } from '@angular/core';
import { ActivatedRoute, NavigationEnd, NavigationStart, Router } from '@angular/router';
import { takeUntil } from 'rxjs';
import { ToastrService } from 'ngx-toastr';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { TranslatePipe } from '@ngx-translate/core';
import { Unsub } from '../../../class/unsub.class';
import { MenuData } from '../../../interfaces/interfaces';
import { AdminService } from '../../../services/admin/admin.service';
import { LoaderService } from '../../../services/loader.service';
import { Menu, NavService } from '../../../services/nav.service';


@Component({
  selector: 'app-admin-menu',
  templateUrl: './admin-menu.component.html',
  styleUrls: ['./admin-menu.component.scss'],
})
export class AdminMenuComponent extends Unsub implements OnInit {
  profileData: MenuData = {};
  @ViewChildren('activeMenuItems') activeMenuItemsRefs!: QueryList<ElementRef>;

  @Input()
  get data(): MenuData {
    return this.profileData;
  }
  set data(value: MenuData) {
    if (value) {
      this.profileData = value;
    }
  }

  public menuItems!: Menu[];
  public url: any;
  public Src: any;
  public sendingResponse: { [key: string]: boolean } = {};
  constructor(
    private adminService: AdminService,
    private tostr: ToastrService,
    private router: Router,
    private navServices: NavService,
    public elRef: ElementRef,
    public sanitizer: DomSanitizer,
    private route: ActivatedRoute,
    public translate: TranslatePipe,
    loaderService: LoaderService
  ) {
    /**
    * This code calls the constructor of the parent class in a subclass. 
    * The super() function is used to initialize the parent class and allows access to its properties and methods. 
    * By calling  super(), the subclass can inherit and use the functionality of the parent class.
    **/
    super(loaderService);

    /**
     *  Initially Used to set the user and permission from localstorage
     *  Later Once the profileData data received from 
     * */
    let users = localStorage.getItem('user');
    
    users ? this.profileData.users = JSON.parse(users) : [];
    let permissions = localStorage.getItem('permissions');
    permissions ? this.profileData.permissions = JSON.parse(permissions) : [];
    this.checkNavActiveOnLoad();
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes['data'].currentValue) {
      this.profileData = changes['data'].currentValue
    }
  }
  ngAfterViewInit() {
    /**
     * Retrieve an array of active menu item using the toArrya()
     * Checking if there are any active menu items, Filter the array to only include menu items that have the CSS class "active".
     * the scrollIntoView() method on the last element in the array to get that element in the view
     */
    const activeMenuItems = this.activeMenuItemsRefs.toArray();
    if (activeMenuItems.length > 0) {
      let newList = activeMenuItems.filter(e => e.nativeElement.classList.contains('active'));
      if (newList[newList.length - 1]) {
        newList[newList.length - 1].nativeElement.scrollIntoView({ behavior: "smooth", block: "start", inline: "nearest" });
      }
    }
  }

  // To set Active on Load
  checkNavActiveOnLoad() {
    this.navServices.adminItems.pipe(takeUntil(this.unSubscribe$)).subscribe({
      next: (menuItems: any) => {
        this.menuItems = menuItems;
        this.router.events.pipe(takeUntil(this.unSubscribe$)).subscribe({
          next: (event: any) => {
            if (event instanceof NavigationStart) {
              const path = location.pathname?.split('/');
              const eventUrl = new URL(event.url, window.location.origin).pathname.split('/');
              if (path[path.length - 2] !== eventUrl[eventUrl.length - 2]) {
                this.closeNavActive();
                const sidelink = document.querySelectorAll('.nav-link.active');
                const sidemenuUl = document.querySelector('.nav-item.active');
                const sidemenuul = document.querySelectorAll('.nav-sub-link.sub-with-sub');
                const subSidemenuUl = document.querySelector('.nav-item.active');
                const subSidemenu = document.querySelectorAll('.nav-sub-link.sub-with-sub');
                sidemenuUl?.classList.remove('active');
                subSidemenuUl?.classList.remove('active');
                sidelink?.forEach((e) => e.classList.remove('active'));
                sidemenuul?.forEach((e) => e.classList.remove('active'));
                subSidemenu?.forEach((e) => e.classList.remove('active'));
              }
            }

            if (event instanceof NavigationEnd) {
              const eventUrl = new URL(event.url, window.location.origin).pathname;
              
              menuItems?.filter((items: any) => {
                if (items.path === eventUrl) {
                  this.setNavActive(items);
                }
                items?.children?.filter((subItems: any) => {
                  if (subItems.path === eventUrl) {
                    this.setNavActive(subItems);
                  }
                  subItems?.children?.filter((subSubItems: any) => {
                    if (subSubItems.path === eventUrl) {
                      this.setNavActive(subSubItems);
                    }
                    subSubItems?.children?.filter((subSubItems1: any) => {
                      if (subSubItems1.path === eventUrl) {
                        this.setNavActive(subSubItems1);
                      }
                    });

                  });

                });

              });
            }
          },
        });
      },
    });
  }
  //Active Nav State
  setNavActive(item: any) {
    this.menuItems?.filter((menuItem) => {
      if (menuItem != item) {
        menuItem.active = false;
        this.navServices.collapseSidebar = false;
      }
      if (menuItem == item) {
        menuItem.active = true;
      }
      if (menuItem.children && menuItem.children.includes(item)) {
        menuItem.active = true;
      }
      if (menuItem.children) {
        menuItem.children?.filter((submenuItems) => {
          if(submenuItems == item){
            menuItem.active = true;
            submenuItems.active = true;
          }
          if (submenuItems.children && submenuItems.children.includes(item)) {
            menuItem.active = true;
            submenuItems.active = true;
          }
          if (submenuItems.children) {
            submenuItems.children?.forEach((subsubmenuItems) => {
              if (
                subsubmenuItems.children &&
                subsubmenuItems.children.includes(item)
              ) {
                menuItem.active = true;
                submenuItems.active = true;
                subsubmenuItems.active = true;
              }
            });
          }
        });
      }
    });
  }

  // Toggle menu
  toggleNavActive(item: any) {
    if (!item.active) {
      this.menuItems?.forEach((a: any) => {
        if (this.menuItems.includes(item)) {
          a.active = false;
        }
        a?.children?.forEach((b: any) => {
          if (a.children.includes(item)) {
            b.active = false;
          }
          b?.children?.forEach((c: any) => {
            if (b.children.includes(item)) {
              c.active = false;
            }
          });
        });
      });
    }
    item.active = !item.active;
  }

  // Close Nav menu
  closeNavActive() {
    this.menuItems?.forEach((a: any) => {
      if (this.menuItems) {
        a.active = false;
      }
      a?.children?.forEach((b: any) => {
        if (a.children) {
          b.active = false;
        }
      });

    });
  }

  ngOnInit(): void {

  }

  closeMenu() {
    document.body.classList.remove('sidenav-toggled');
  }

  clearCache(buttonId) {
    const data = {
    };
    this.sendingResponse[buttonId] = true;
    this.adminService.clearCache(data).subscribe({
      next: (res) => {
        this.sendingResponse[buttonId] = false;
        if (res.success) {
          this.tostr.success(this.translate.transform(res.success));
        }
        if (res.error) {
          this.tostr.error(this.translate.transform(res.error));
        }
      },
      error: () => {
        this.sendingResponse[buttonId] = false;
      },
    });
  }

  getSanitizedSVG(svgContent: string): SafeHtml {
    return this.sanitizer.bypassSecurityTrustHtml(svgContent);
  }
}
