import { Component, ViewChild, ElementRef, Renderer2, HostListener, ChangeDetectorRef } from '@angular/core';
import { Menu, NavService } from '../../services/navservice';
import { Subscription, fromEvent } from 'rxjs';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { NavigationEnd, Router } from '@angular/router';
import { checkHoriMenu, switcherArrowFn } from './sidebar';
import { ConfigPermissionService } from '../../services/config-permission.service';
import { ConfigPermissionModel, MenuBodyModel, MyConfigPermissionModel } from '../../model/config-permission.model';
import { TokenService } from '../../services/token.service';
import { ViewportScroller } from '@angular/common';
import { ExcelReportService } from '../../services/excel-report.service';
import { MyTemplateFileMiniModel } from '../../model/template-file-mini.model';

@Component({
  selector: 'app-sidebar',
  templateUrl: './sidebar.component.html',
  styleUrls: ['./sidebar.component.scss'],
})
export class SidebarComponent {
  // Addding sticky-pin
  scrolled = false;
  screenWidth: number;
  isCommonRoute: boolean = false;
  isESSRoute: boolean = false;
  eventTriggered: boolean = false;
  public localdata = localStorage;

  @HostListener('window:scroll', [])
  onWindowScroll() {

    const navScrollElement =
      this.elementRef.nativeElement.querySelector('.nav-scroll');
    this.scrolled = window.scrollY > 10;

    const sections = document.querySelectorAll('.side-menu__item');
    const scrollPos =
      window.scrollY ||
      this.elementRef.nativeElement.ownerDocument.documentElement.scrollTop ||
      document.body.scrollTop;

    sections.forEach((ele, i) => {
      const currLink = sections[i];
      const val: any = currLink.getAttribute('value');
      const refElement: any = document.querySelector('#' + val);

      // Add a null check here before accessing properties of refElement
      if (refElement !== null) {
        const scrollTopMinus = scrollPos + 73;
        if (
          refElement.offsetTop <= scrollTopMinus &&
          refElement.offsetTop + refElement.offsetHeight > scrollTopMinus
        ) {
          if (navScrollElement) {
            this.renderer.removeClass(navScrollElement, 'active');
          }
          currLink.classList.add('active');
        } else {
          currLink.classList.remove('active');
        }
      }
    });
  }
  //////

  public windowSubscribe$!: Subscription;
  options = { autoHide: false, scrollbarMinSize: 100 };
  icon!: SafeHtml;

  public menuItems: Menu[] = [];
  public menuitemsSubscribe$!: Subscription;
  user_level? = ""
  configPermission: { loading: boolean, data: ConfigPermissionModel } = { loading: false, data: new MyConfigPermissionModel() }
  isEssRoute: boolean = false;
  isAdminRoute: boolean = false;
  previousUrl: string = '';
  currentUrl: string = '';
  showSideMenu: boolean = false;
  constructor(
    private navServices: NavService,
    private sanitizer: DomSanitizer,
    public router: Router,
    public renderer: Renderer2,
    private elementRef: ElementRef,
    private configPermissionService: ConfigPermissionService,
    private cdr: ChangeDetectorRef,
    private tokenService: TokenService,
    private viewScroller: ViewportScroller,
    private excelReportService: ExcelReportService
  ) {
    this.screenWidth = window.innerWidth;
    this.user_level = this.tokenService.getUser()?.user_level
  }

  ngOnInit() {
    this.currentUrl = this.router.url
    this.isESSRoute = this.currentUrl.includes('/ess');
    this.isAdminRoute = this.currentUrl.includes('/admin');
    this.showSideMenu = this.currentUrl.includes('my-skill-x-module') ||
      this.currentUrl.includes('employee-self-service') ||
      this.currentUrl.includes('ess/profile') ||
      this.currentUrl.includes('ess/competency-mapping') ||
      this.currentUrl.includes('ess/job-description')
    if (this.showSideMenu) {
      const html: any = this.elementRef.nativeElement.ownerDocument.documentElement;;
      html.style = '';
      html.setAttribute('data-nav-layout', 'horizontal');
    } else {
      const html: any = this.elementRef.nativeElement.ownerDocument.documentElement;
      html.setAttribute('data-nav-layout', 'vertical');
    }

    // this.menuitemsSubscribe$ = this.navServices.items.subscribe((items) => {
    //   this.menuItems = items;
    // });
    // this.getConfigPermissionByUserLevel()
    this.menuitemsSubscribe$ = this.navServices.items.subscribe((items) => {
      this.changeMenu()
    });
    this.ParentActive();
    this.checkUrlChanges();
    // this.router.events.subscribe((event) => {
    //   sessionStorage.setItem('currentUrl', this.router.url)
    //   if (event instanceof NavigationEnd) {
    //     this.ParentActive();
    //   }
    // });
    if (window.innerWidth <= 992) {
      document.documentElement?.setAttribute('toggled', 'close');
    }
    const WindowResize = fromEvent(window, 'resize');
    // subscribing the Observable
    if (WindowResize) {
      this.windowSubscribe$ = WindowResize.subscribe(() => {
        // to check and adjst the menu on screen size change
        checkHoriMenu();
      });
    }
    switcherArrowFn();
    checkHoriMenu();
    if (document.documentElement.getAttribute('data-nav-layout') == 'horizontal' && window.innerWidth > 992) {
      this.closeNavActive()
    }


  }

  checkUrlChanges(): void {

    this.router.events.subscribe((event) => {
      if (event instanceof NavigationEnd) {
        this.ParentActive();
      }
    });
    this.router.events.subscribe((event) => {
      if (event instanceof NavigationEnd) {
        this.previousUrl = this.currentUrl; // Save the previous URL
        this.currentUrl = event.url; // Update to the new URL

        // Check if there's a change between /installer and /admin
        if (
          (this.previousUrl.includes('/ess') && this.currentUrl.includes('/admin')) ||
          (this.previousUrl.includes('/admin') && this.currentUrl.includes('/ess'))
        ) {
          // console.log('URL changed between /installer and /admin.');
          // Implement any logic needed when changing between /installer and /admin
        }

        // Update the boolean values
        this.isESSRoute = this.currentUrl.includes('/ess');
        this.isAdminRoute = this.currentUrl.includes('/admin');
        this.showSideMenu = this.currentUrl.includes('my-skill-x-module') ||
          this.currentUrl.includes('employee-self-service') ||
          this.currentUrl.includes('ess/profile') ||
          this.currentUrl.includes('ess/competency-mapping') ||
          this.currentUrl.includes('ess/job-description')
        if (this.showSideMenu) {
          const html: any = this.elementRef.nativeElement.ownerDocument.documentElement;;
          html.style = '';
          html.setAttribute('data-nav-layout', 'horizontal');
        } else {
          const html: any = this.elementRef.nativeElement.ownerDocument.documentElement;
          html.setAttribute('data-nav-layout', 'vertical');
        }
        // Log to console for verification
        this.changeMenu()
      }
    });
  }


  changeMenu() {
    if (this.isESSRoute) {
      this.menuitemsSubscribe$ = this.navServices.items.subscribe((items) => {
        if (!this.previousUrl.includes('/self-evaluation') && !this.previousUrl.includes('/supervisor-evaluation')) {
          this.menuItems = this.navServices.getCustomerMenu();
          this.ParentActive()
        }
      });
      // if(this.tokenService.getUser().role=='manager'){
      //   this.menuitemsSubscribe$ = this.navServices.items.subscribe((items) => {
      //     this.menuItems = this.navServices.getCommonMenu();
      //   });
      // }
      // else{
      //   this.menuitemsSubscribe$ = this.navServices.items.subscribe((items) => {
      //     this.menuItems = this.navServices.getProjectEmpMenu();
      //   });
      // }
    } else {
      this.menuitemsSubscribe$ = this.navServices.items.subscribe((items) => {
        if (!this.previousUrl.includes('/admin/') && !this.previousUrl.includes('/dashboard')) {
          this.menuItems = this.navServices.getAdminMenu()
          this.ParentActive()
          this.excelReportService.getTemplateFileLists().subscribe({
            next: response => {
              const submenuExcel = response.map((e, i) => ({
                id: 'mExport' + i,
                path: 'admin/excel-export/' + e.itemId + "?template=" + e.templateId + "&name=" + e.fileName,
                title: e.itemId + '.' + e.tdesc,
                type: 'link', show: true
              }))
              if (submenuExcel.length) {
                this.menuItems.push({
                  title: 'ExcelReport',
                  type: 'sub',
                  selected: false,
                  active: false,
                  path: '',
                  id: 'm7',
                  show: true,
                  icon: 'assets/img/icons-menu/Report.png',
                  children: submenuExcel
                })
              }
            }
          })

        }
      });
    }
  }
  addMenu() {

  }
  getConfigPermissionByUserLevel() {
    this.configPermission.loading = true
    this.configPermissionService.getByUserLevel(this.user_level!).subscribe({
      next: response => {
        this.configPermission.data = new MyConfigPermissionModel(response)
        this.menuItems.forEach(x => {
          // เปิดทุกเมนู
          // x.show = true
          // x.children?.forEach(y => {
          //   y.show = true
          // })

          // เปิดตาม config
          const configMenu = this.configPermission.data.menuBody.find(y => y.id == x.id)
          if (configMenu) {
            x.show = configMenu.show
            x.children?.forEach(y => {
              const configChildren = configMenu.children.find(z => z.id == y.id)
              if (configChildren) {
                y.show = configChildren.show
              }
            })
          }
        })
        let path404check = '/404page'
        this.menuItems.forEach(x => {
          const children = x.children?.find(y => y.path == sessionStorage.getItem('currentUrl'))
          if (children?.show && path404check == '/404page') {
            path404check = children.path || '/404page'
          }
        })
        if (path404check == '/404page') {
          this.menuItems.forEach(x => {
            if (x.show && path404check == '/404page') {
              x.children?.forEach(y => {
                if (y.show) {
                  path404check = y.path || '404page'
                }
              })
            }
          })
        }
        this.router.navigate([path404check]);
        this.configPermission.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.configPermission.loading = false
        this.cdr.detectChanges()
      }
    })
  }

  // decodeJWT(token: string) {
  //   let base64Url = token.split('.')[1];
  //   let base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
  //   let jsonPayload = decodeURIComponent(atob(base64).split('').map(function (c) {
  //     return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  //   }).join(''));
  //   return JSON.parse(jsonPayload);
  // }



  //Active Nav State
  setNavActive(item: any) {
    this.viewScroller.scrollToPosition([0, 0]);
    this.menuItems?.filter((menuItem: Menu) => {
      if (menuItem !== item) {
        menuItem.active = false;
        menuItem.selected = false;
        this.navServices.collapseSidebar = false;
      }
      if (menuItem.children && menuItem.children.includes(item)) {
        menuItem.active = true;
        menuItem.selected = true;
      }
      if (menuItem.children) {
        menuItem.children?.filter((submenuItems) => {
          if (submenuItems.children && submenuItems.children.includes(item)) {
            menuItem.active = true;
            submenuItems.active = true;
            menuItem.selected = true;
            submenuItems.selected = true;
          }
          if (submenuItems.children) {
            submenuItems.children?.forEach((subsubmenuItems) => {
              if (
                subsubmenuItems.children &&
                subsubmenuItems.children.includes(item)
              ) {
                menuItem.active = true;
                submenuItems.active = true;
                subsubmenuItems.active = true;
                menuItem.selected = true;
                submenuItems.selected = true;
                subsubmenuItems.selected = 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;
          } else {
            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;
        }
      });
    });
  }

  ParentActive() {
    // this.menuItems.map((element: any) => {
    //   if (element.children) {
    //     element.active = false;
    //     element.selected = false;
    //     element.children.map((ele: any) => {

    //       if (ele.path == this.router.url) {
    //         element.active = true;
    //         element.selected = true;
    //       }
    //       if (ele.children) {
    //         ele.active = false;
    //         ele.children.map((child1: any) => {
    //           if (child1.path == this.router.url) {
    //             element.active = true;
    //             element.selected = true;
    //             ele.active = true;
    //             ele.selected = true;
    //           }
    //         });
    //       }
    //     });
    //   }
    // });
  }

  @ViewChild('iconContainer', { static: true }) iconContainer!: ElementRef;
  getSanitizedSVG(svgContent: string, menu: any): SafeHtml {
    const svg = this.renderer.createElement(
      'svg',
      'http://www.w3.org/2000/svg'
    );
    svg.innerHTML = svgContent;
    svg.classList.add('side-menu__icon');
    this.renderer.listen(svg, 'click', () => {
      this.toggleNavActive(menu);
    });
    // return svg;
    return this.sanitizer.bypassSecurityTrustHtml(svgContent);
  }
  ngOnDestroy() {
    this.menuitemsSubscribe$.unsubscribe();
    this.windowSubscribe$.unsubscribe();
    this.elementRef.nativeElement.ownerDocument.documentElement,
      'data-nav-layout',
      'vertical';
    const WindowResize = fromEvent(window, 'resize');
    // subscribing the Observable
    if (WindowResize) {
      this.windowSubscribe$ = WindowResize.subscribe(() => {
        // to check and adjst the menu on screen size change
        checkHoriMenu();
      });
    }
  }

  @HostListener('window:resize', ['$event'])
  onResize(event: any): void {
    this.screenWidth = window.innerWidth;

    // Check if the event hasn't been triggered and the screen width is less than or equal to your breakpoint
    if (!this.eventTriggered && this.screenWidth <= 992) {
      document.documentElement?.setAttribute('toggled', 'close')


      // Trigger your event or perform any action here
      this.eventTriggered = true; // Set the flag to true to prevent further triggering
    } else if (this.screenWidth > 992) {
      // Reset the flag when the screen width goes beyond the breakpoint
      this.eventTriggered = false;
    }
  }
}
