import { ApplicationConfig, inject, provideAppInitializer, provideZonelessChangeDetection } from '@angular/core';
import { provideRouter, withHashLocation } from '@angular/router';
import { routes } from './app.routes';
import { HTTP_INTERCEPTORS, provideHttpClient, withInterceptorsFromDi } from '@angular/common/http';
import { TokenInterceptor } from './_shared/token-interceptor';
import { IconSettingsService, ICON_SETTINGS, KENDO_SVGICON } from "@progress/kendo-angular-icons";
import { MyIconService } from "./_shared/services/my-icon.service";
import { CommonService } from './_shared/services/common.service';
import { AuthClass } from './_shared/utils/authClass';
import { provideAnimations } from '@angular/platform-browser/animations';
import { KENDO_CHECKBOX, KENDO_NUMERICTEXTBOX, KENDO_SWITCH, KENDO_TEXTAREA, KENDO_TEXTBOX } from '@progress/kendo-angular-inputs';
import { KENDO_COMBOBOX, KENDO_MULTISELECT } from '@progress/kendo-angular-dropdowns';
import { KENDO_DATEPICKER } from '@progress/kendo-angular-dateinputs';
import { KENDO_GRID } from '@progress/kendo-angular-grid';
import { KENDO_WINDOW } from '@progress/kendo-angular-dialog';
import { KENDO_UPLOAD } from '@progress/kendo-angular-upload';
import { KENDO_TOOLTIP } from '@progress/kendo-angular-tooltip';
import { WinHeightPipe } from './_shared/pipes/win-height.pipe';
import { WinWidthPipe } from './_shared/pipes/win-width.pipe';
import { GlobalBarComponent } from './_shared/global-bar/global-bar.component';
import { ReactiveFormsModule } from '@angular/forms';
import { AsyncPipe } from '@angular/common';
import { Title } from '@angular/platform-browser';
import { SafePipe } from './_shared/pipes/safe.pipe';
import { RedirectGuard } from './_shared/redirect.guard';
import { FastSpinnerComponent } from './_shared/elements/fast-spinner.component';
import { FastOverlayComponent } from './_shared/elements/fast-overlay.component';
import { FastTipDirective } from './_shared/elements/fast-tip.directive';
import { FastTipContainerComponent } from './_shared/elements/fast-tip-container.component';
import { FastFrameComponent } from './_shared/elements/fast-frame.component';
import { FastGridComponent } from './_shared/elements/fast-grid.component';
import { FastWindowComponent } from './_shared/elements/fast-window.component';
import { FastHeaderComponent } from './_shared/elements/fast-header.component';
import { FastButtonComponent } from './_shared/elements/fast-button.component';
import { FastComboboxComponent } from './_shared/elements/fast-combobox.component';
import { FastHRComponent } from './_shared/elements/fast-hr.component';
import { FastLabelComponent } from './_shared/elements/fast-label.component';
import { FastTextboxComponent } from './_shared/elements/fast-textbox.component';
import { FastMultiselectComponent } from './_shared/elements/fast-multiselect.component';
import { FastDatePickerComponent } from './_shared/elements/fast-datepicker.component';
import { FastNumericTextBoxComponent } from './_shared/elements/fast-numerictextbox.component';
import { KENDO_CONTEXTMENU } from '@progress/kendo-angular-menu';
import { FastUploadComponent } from './_shared/elements/fast-upload.component';
import { AuthService } from './_shared/services/auth.service';
import { tap, firstValueFrom } from 'rxjs';
import { uid } from './_shared/utils/util';

// These get set in initConfig():
export let appConfig: ApplicationConfig;

export function initConfig() {
  appConfig = {
    providers: [
      Title,
      SafePipe, //this is so that the pipe can be used from within other pipes and components, not just in templates
      RedirectGuard,
      provideZonelessChangeDetection(),
      provideRouter(routes, withHashLocation()),
      provideHttpClient(withInterceptorsFromDi()),
      provideAnimations(),
      provideAppInitializer(() => {
        const authService = inject(AuthService);
        const commonService = inject(CommonService);
        return firstValueFrom(authService.checkLoginStatusOnInit().pipe(
          tap(() => {
            // If login check was successful, then refresh common data
            if (authService.isLoggedIn()) {
              console.log('App Initializer: Logged in. Refreshing common data...');
              // commonService.refreshCommonData.set({ uid: uid() });
              commonService.getServerThemeName.set(uid());
            } else {
              console.log('App Initializer: Not logged in. Skipping common data refresh.');
            }
          })
          // If initial check fails, it's already handled by authService.isLoggedIn.set(false)
          // and we don't want to block the app from starting entirely.
          // However, if the guard is to correctly kick in, this needs to complete.
          // We'll let the error propagate if it's truly an initialization failure,
          // but for a 401 on checkCookieStatus, authService handles setting isLoggedIn.
          // The key is that this *must* finish before routing.
        ));
      }),
      // provideAppInitializer(() => {
      //   const initializerFn = (commonServiceFactory)(inject(CommonService));
      //   return initializerFn();
      // }),
      { provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true },
      { provide: ICON_SETTINGS, useValue: { type: "svg" } },
      { provide: IconSettingsService, useClass: MyIconService }
    ]
  };
}

export const FAST_KENDO_COMMON = [KENDO_SVGICON, KENDO_CHECKBOX, KENDO_COMBOBOX, KENDO_DATEPICKER, KENDO_GRID, KENDO_MULTISELECT, KENDO_NUMERICTEXTBOX, KENDO_SWITCH, KENDO_TEXTAREA, KENDO_TEXTBOX, KENDO_TOOLTIP, KENDO_UPLOAD, KENDO_WINDOW, KENDO_CONTEXTMENU] as const;
export const FAST_PAGE_COMMON = [AsyncPipe, GlobalBarComponent, ReactiveFormsModule, WinHeightPipe, WinWidthPipe, FastSpinnerComponent, FastOverlayComponent, FastTipDirective, FastTipContainerComponent, FastFrameComponent, FastGridComponent, FastWindowComponent, FastHeaderComponent, FastButtonComponent, FastComboboxComponent, FastHRComponent, FastLabelComponent, FastTextboxComponent, FastMultiselectComponent, FastDatePickerComponent, FastNumericTextBoxComponent, FastUploadComponent] as const;

export function commonServiceFactory(service: CommonService) {
  return () => {
    return new Promise<void>((resolve) => {
      service.serverSettings$.subscribe({
        next: result => {
          AuthClass.ServerSettings = result;
          AuthClass.ServerSettings.mainSiteUrl = window.location.protocol + "//" + window.location.host;
          resolve();
        },
        error: err => {
          console.log(err.message);
        }
      });
    });
  }
}
