import { Component, inject, OnInit, ChangeDetectorRef } from '@angular/core';
import { ActivatedRoute, NavigationEnd, Router, RouterOutlet } from '@angular/router';
import * as tablerIcons from '@ng-icons/tabler-icons';
import * as tablerIconsFill from '@ng-icons/tabler-icons/fill';
import * as lucideIcons from '@ng-icons/lucide';
import { provideIcons } from '@ng-icons/core';
import { Title } from '@angular/platform-browser';
import { filter, map, mergeMap } from 'rxjs';
import { AuthService } from './core/services/auth.service';

@Component({
  selector: 'app-root',
  imports: [RouterOutlet],
  templateUrl: './app.html',
  styleUrls: ['./app.scss'],
  viewProviders: [
    provideIcons({ ...tablerIcons, ...tablerIconsFill, ...lucideIcons }),
  ],
})
export class App implements OnInit {
  private titleService = inject(Title);
  private router = inject(Router);
  private activatedRoute = inject(ActivatedRoute);
  private authService = inject(AuthService);
  private cdr = inject(ChangeDetectorRef);

  async ngOnInit(): Promise<void> {
    this.setupTitleListener();
    
    setTimeout(async () => {
      await this.initializeAuth();
    });
  }

  private async initializeAuth(): Promise<void> {
    try {
      const isAuthenticated = await this.authService.initialize();
      
      setTimeout(() => {
        this.handleInitialNavigation(isAuthenticated);
      });
      
    } catch (error) {
      console.error('Error during authentication initialization:', error);
      setTimeout(() => {
        this.router.navigate(['/auth/login']);
      });
    }
  }

  private handleInitialNavigation(isAuthenticated: boolean): void {
    const currentUrl = this.router.url;
    
    if (!isAuthenticated && this.shouldRedirectToLogin(currentUrl)) {
      this.router.navigate(['/auth/login']);
    } else if (isAuthenticated && this.shouldRedirectToDashboard(currentUrl)) {
      this.router.navigate(['/dcb-dashboard']);
    }
    
    this.cdr.detectChanges();
  }

  private shouldRedirectToLogin(url: string): boolean {
    return url === '/' || !this.isPublicRoute(url);
  }

  private shouldRedirectToDashboard(url: string): boolean {
    return url === '/' || this.isPublicRoute(url);
  }

  private isPublicRoute(url: string): boolean {
    const publicRoutes = ['/auth/login', '/auth/reset-password', '/auth/forgot-password'];
    return publicRoutes.some(route => url.startsWith(route));
  }

  private setupTitleListener(): void {
    this.router.events
      .pipe(
        filter((event): event is NavigationEnd => event instanceof NavigationEnd),
        map(() => {
          let route = this.activatedRoute;
          while (route.firstChild) {
            route = route.firstChild;
          }
          return route;
        }),
        mergeMap((route) => route.data)
      )
      .subscribe((data) => {
        if (data['title']) {
          this.titleService.setTitle(`${data['title']} | DCB BO Admin`);
        }
      });
  }
}
