/* eslint-disable @typescript-eslint/no-unused-vars */
// angular
import { Router, NavigationEnd } from '@angular/router';
import { DOCUMENT } from '@angular/common';
import { Component, DestroyRef, Inject, ElementRef, OnInit, Renderer2, HostListener, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { filter } from 'rxjs/operators';

// libs
import { NgScrollbarModule } from 'ngx-scrollbar';
import { TranslateModule } from '@ngx-translate/core';

// app
import { ROUTES } from './sidebar-items';
import { AuthService } from 'src/app/core/service/auth.service';
import { AccountCategoryService } from '../../services/account.category.service';
import { RouteInfo } from './sidebar.metadata';
import { SharedModule } from 'src/app/shared/shared.module';

@Component({
	selector: 'app-sidebar',
	templateUrl: './sidebar.component.html',
	styleUrls: ['./sidebar.component.scss'],
	standalone: true,
	imports: [SharedModule, NgScrollbarModule, TranslateModule],
})
export class SidebarComponent implements OnInit {
	sidebarItems!: RouteInfo[];
	innerHeight?: number;
	bodyTag!: HTMLElement;
	listMaxHeight?: string;
	listMaxWidth?: string;
	userFullName?: string;
	userImg?: string;
	userType?: string;
	headerHeight = 60;
	currentRoute?: string;
	menuIcon = 'radio_button_checked';
	private readonly destroyRef = inject(DestroyRef);

	constructor(
		@Inject(DOCUMENT) private document: Document,
		private renderer: Renderer2,
		public elementRef: ElementRef,
		private authService: AuthService,
		private router: Router,
		private accountCategoryService: AccountCategoryService,
	) {
		this.elementRef.nativeElement.closest('body');
		this.router.events
			.pipe(
				filter((event): event is NavigationEnd => event instanceof NavigationEnd),
				takeUntilDestroyed(this.destroyRef)
			)
			.subscribe(() => {
				// close sidebar on mobile screen after menu select
				this.renderer.removeClass(this.document.body, 'overlay-open');
			});
	}

	@HostListener('window:resize', ['$event'])
	windowResizecall() {
		this.setMenuHeight();
		this.checkStatuForResize(false);
	}

	@HostListener('document:mousedown', ['$event'])
	onGlobalClick(event: Event): void {
		if (!this.elementRef.nativeElement.contains(event.target)) {
			this.renderer.removeClass(this.document.body, 'overlay-open');
		}
	}

	callToggleMenu(event: Event, length: number) {
		if (length > 0) {
			const parentElement = (event.target as HTMLInputElement).closest('li');
			const activeClass = parentElement?.classList.contains('active');

			if (activeClass) {
				this.renderer.removeClass(parentElement, 'active');
			} else {
				this.renderer.addClass(parentElement, 'active');
			}
		}
	}

	ngOnInit() {
		if (this.authService.currentUserValue) {
			this.userFullName =
				this.authService.currentUserValue.firstName +
				' ' +
				this.authService.currentUserValue.lastName;
			this.userImg = this.authService.currentUserValue.img;
			this.userType = 'Admin';
			this.sidebarItems = ROUTES.filter((sidebarItem) => sidebarItem);

			this.accountCategoryService
				.getCategories()
				.pipe(takeUntilDestroyed(this.destroyRef))
				.subscribe(categories => {
					var accounts = this.sidebarItems.filter(x => x.id === 'accounts');
					accounts[0].submenu = [];
					for (var category of categories) {
						accounts[0].submenu.push({
							path: '/account-category/' + category.id,
							title: category.name!,
							iconType: '',
							icon: '',
							class: 'ml-menu',
							groupTitle: false,
							badge: '',
							badgeClass: '',
							submenu: [],

						});
					}
				});
		}

		// this.sidebarItems = ROUTES.filter((sidebarItem) => sidebarItem);
		this.initLeftSidebar();
		this.bodyTag = this.document.body;
	}

	initLeftSidebar() {
		// eslint-disable-next-line @typescript-eslint/no-this-alias
		const _this = this;
		// Set menu height
		_this.setMenuHeight();
		_this.checkStatuForResize(true);
	}

	setMenuHeight() {
		this.innerHeight = window.innerHeight;
		const height = this.innerHeight - this.headerHeight;
		this.listMaxHeight = height + '';
		this.listMaxWidth = '500px';
	}

	isOpen() {
		return this.bodyTag.classList.contains('overlay-open');
	}

	checkStatuForResize(firstTime: boolean) {
		if (window.innerWidth < 1170) {
			this.renderer.addClass(this.document.body, 'ls-closed');
		} else {
			this.renderer.removeClass(this.document.body, 'ls-closed');
		}
	}

	mouseHover() {
		const body = this.elementRef.nativeElement.closest('body');
		if (body.classList.contains('submenu-closed')) {
			this.renderer.addClass(this.document.body, 'side-closed-hover');
			this.renderer.removeClass(this.document.body, 'submenu-closed');
		}
	}

	mouseOut() {
		const body = this.elementRef.nativeElement.closest('body');
		if (body.classList.contains('side-closed-hover')) {
			this.renderer.removeClass(this.document.body, 'side-closed-hover');
			this.renderer.addClass(this.document.body, 'submenu-closed');
		}
	}

	mobileMenuSidebarOpen(event: Event, className: string) {
		const hasClass = (event.target as HTMLInputElement).classList.contains(
			className
		);
		if (hasClass) {
			this.renderer.removeClass(this.document.body, className);
		} else {
			this.renderer.addClass(this.document.body, className);
		}
	}

	callSidemenuCollapse() {
		const hasClass = this.document.body.classList.contains('side-closed');
		if (hasClass) {
			this.renderer.removeClass(this.document.body, 'side-closed');
			this.renderer.removeClass(this.document.body, 'submenu-closed');
			this.menuIcon = 'radio_button_checked';
		} else {
			this.renderer.addClass(this.document.body, 'side-closed');
			this.renderer.addClass(this.document.body, 'submenu-closed');
			this.menuIcon = 'radio_button_unchecked';
		}

		const sideClosedHover =
			this.document.body.classList.contains('side-closed');
		if (sideClosedHover) {
			this.renderer.removeClass(this.document.body, 'side-closed-hover');
		}
	}

	logout() {
		this.authService.logout()
			.pipe(takeUntilDestroyed(this.destroyRef))
			.subscribe((res) => {
				if (!res.success) {
					console.log('sidebar.logout');
					this.router.navigate(['/authentication/signin']);
				}
			});
	}
}
