import { Component, ChangeDetectionStrategy, HostListener, OnInit, AfterContentInit, inject, signal, effect, ChangeDetectorRef, ViewChild, AfterViewInit } from '@angular/core';
import { handleKeys, selectInputTextOnClick } from './utils/util';
import { CommonService } from './services/common.service';
import { MessageService } from './services/message.service';
import { BehaviorSubject } from 'rxjs';
import { ActivatedRoute, RouterOutlet } from '@angular/router';
import { environment } from '../../environments/environment';
import { uid } from '../_shared/utils/util';
import { AsyncPipe } from '@angular/common';
import { KENDO_TOOLTIP } from '@progress/kendo-angular-tooltip';
import { FastTipDirective } from './elements/fast-tip.directive';
import { ADAPTIVE_SETTINGS, AdaptiveService } from '@progress/kendo-angular-utils';
import { AuthService } from './services/auth.service';
import { FastToastComponent } from "./elements/fast-toast.component";
import { ToastService } from './services/fast-toast.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [KENDO_TOOLTIP, RouterOutlet, AsyncPipe, FastTipDirective, FastToastComponent],
  providers: [
    AdaptiveService,
    //The Kendo adaptive settings small layout seems to have display issues on mobile
    //so we skipt it and use the medium settings, even for small resolutions
    { provide: ADAPTIVE_SETTINGS, useValue: { small: 0, medium: 850 } }
  ],
})
export class AppComponent implements OnInit, AfterContentInit, AfterViewInit {
  @ViewChild('toastComponent') toastComponent: FastToastComponent;

  @HostListener('keydown', ['$event']) onKeyDown(e: KeyboardEvent) {
    handleKeys(e);
  }
  @HostListener('mousedown', ['$event']) onMouseDown(e: MouseEvent) {
    selectInputTextOnClick(e);
  }

  commonService = inject(CommonService);
  messageService = inject(MessageService);
  toastService = inject(ToastService);
  activatedRoute = inject(ActivatedRoute);
  private readonly authService = inject(AuthService);
  private readonly cdr = inject(ChangeDetectorRef);

  isDev: boolean = !environment.production;
  isRoot: boolean = window.location.hash.toLowerCase() === '#/root';

  //use ngAfterContentInit instead of ngAfterViewInit because ngAfterViewInit causes an "Expression has changed after it was checked" error
  ngAfterContentInit(): void {
    this.activatedRoute.queryParams.subscribe(x => {
      const isTopless = x['topless'] ? true : false;
      this.isToplessSubject.next(isTopless);
      this.cdr.detectChanges(); // Trigger CD as this update might not be detected
    });
  }

  ngAfterViewInit(): void {
    this.toastService.toastComponent = this.toastComponent;
  }

  isToplessSubject = new BehaviorSubject<boolean>(true);
  isTopless$ = this.isToplessSubject.asObservable();

  isDarkTheme = signal(false);

  constructor() {
    effect(() => {
      const serverThemeName = this.commonService.serverThemeNameRes.value();
      if (serverThemeName === undefined || this.commonService.serverThemeNameRes.isLoading())
        return;

      this.applyTheme(serverThemeName);
      this.cdr.detectChanges(); // Trigger CD as this effect runs outside Angular's direct detection cycle
    });

  }

  ngOnInit(): void {
    this.applyTheme('useExisting');
    this.authService.restoreSavedRoute();
  }

  applyTheme(themeNameToApply: 'useExisting' | 'light' | 'dark') {
    const darkThemeNames = ['dark', 't2', 't3'];
    const needsSaving = themeNameToApply !== 'useExisting';

    if (themeNameToApply === 'useExisting') {
      const storedThemeName = localStorage.getItem('theme');
      themeNameToApply = storedThemeName && darkThemeNames.includes(storedThemeName) ? 'dark' : 'light';
    } else
      localStorage.setItem('theme', themeNameToApply);

    const elem = document.body;

    const needsLightClass = themeNameToApply === 'light' && !elem.classList.contains('light');
    if (needsLightClass) {
      elem.classList.remove('scheme-dark', 'dark');
      elem.classList.add('light', 'scheme-light');
    }

    const needsDarkClass = themeNameToApply === 'dark' && !elem.classList.contains('dark');
    if (needsDarkClass) {
      elem.classList.remove('scheme-light', 'light');
      elem.classList.add('dark', 'scheme-dark');
    }

    this.isDarkTheme.set(themeNameToApply === 'dark'); //this is for the theme icon

    if (needsSaving)
      this.commonService.saveThemeToServer.set({ uid: uid(), themeName: themeNameToApply })
  }
}
