import { ApplicationConfig, inject, Injector, provideAppInitializer, provideZoneChangeDetection } 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 { 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_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 { FastToggleComponent } from './_shared/elements/fast-toggle.component';
import { FastGridColComponent } from './_shared/elements/fast-grid-col.component';
import { FastGridDateFilterCell } from './_shared/elements/fast-grid-date-filter-cell.component';
import { FastListviewComponent } from './_shared/elements/fast-listview.component';
import { FastTextAreaComponent } from './_shared/elements/fast-textarea.component';
import { FastTreeviewComponent } from './_shared/elements/fast-treeview.component';
import { FastContextMenuComponent } from './_shared/elements/fast-contextmenu.component';
import { FastCheckboxComponent } from './_shared/elements/fast-checkbox.component';
import { FastAutocompleteComponent } from './_shared/elements/fast-autocomplete.component';
import { FastButtonGroupComponent } from './_shared/elements/fast-buttongroup.component';
import { FastTabGroupComponent } from './_shared/elements/fast-tabgroup.component';
import { FastTabHeaderComponent } from './_shared/elements/fast-tabheader.component';
import { FastTabPanelComponent } from './_shared/elements/fast-tabpanel.component';
import { FastTabContentDirective } from './_shared/directives/fast-tab-content.directive';
import { FastTabLabelDirective } from './_shared/directives/fast-tab-label.directive';
import { FastIconService } from './_shared/services/fast-icon.service';
import { FastSVGComponent } from './_shared/elements/fast-svg.component';
import { AuthService } from './_shared/services/auth.service';
import { CommonService } from './_shared/services/common.service';
import { firstValueFrom, switchMap, filter, take, of } from 'rxjs';
import { uid } from './_shared/utils/util';
import { toObservable } from '@angular/core/rxjs-interop';
import { LoggerService } from './_shared/services/logger.service';
import { FastPanelbarComponent } from './_shared/elements/fast-panelbar.component';
import { FastPanelbarItemComponent } from './_shared/elements/fast-panelbar-item.component';

// 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,
      //provideZoneChangeDetection needed for certain features of kendo grid component
      //after full kendo removal, switch to zoneless
      provideZoneChangeDetection(),
      provideRouter(routes, withHashLocation()),
      provideHttpClient(withInterceptorsFromDi()),
      provideAnimations(),
      provideAppInitializer(() => {
        const authService = inject(AuthService);
        const commonService = inject(CommonService); // Inject CommonService here
        const logger = inject(LoggerService);
        const injector = inject(Injector);
        return firstValueFrom(authService.checkLoginStatusOnInit().pipe(
          switchMap(() => {
            // If login check was successful, then refresh common data
            if (authService.isLoggedIn()) {
              logger.log('App Initializer: Logged in. Refreshing common data...');
              commonService.refreshCommonData.set({ uid: uid() });
              commonService.getServerThemeName.set(uid());

              // Wait for common data to load before proceeding
              return toObservable(commonService.commonDataRes.value, { injector }).pipe(
                filter(data => !!data),
                take(1)
              );
            } else {
              logger.log('App Initializer: Not logged in. Skipping common data refresh.');
              return of(null);
            }
          })
          // 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 iconService = inject(FastIconService);
        iconService.loadSprite()
      }),
      { provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true },
    ]
  };
}

export const FAST_KENDO_COMMON = [KENDO_CHECKBOX, KENDO_COMBOBOX, KENDO_DATEPICKER, KENDO_GRID, KENDO_MULTISELECT, KENDO_NUMERICTEXTBOX, KENDO_SWITCH, KENDO_TEXTAREA, KENDO_TEXTBOX, KENDO_TOOLTIP, KENDO_UPLOAD, KENDO_CONTEXTMENU] as const;
export const FAST_PAGE_COMMON = [AsyncPipe, GlobalBarComponent, ReactiveFormsModule, WinHeightPipe, WinWidthPipe, FastSpinnerComponent, FastOverlayComponent, FastTipDirective, FastTabContentDirective, FastTabLabelDirective, FastTipContainerComponent, FastFrameComponent, FastGridComponent, FastWindowComponent, FastHeaderComponent, FastButtonComponent, FastComboboxComponent, FastHRComponent, FastLabelComponent, FastTextboxComponent, FastMultiselectComponent, FastDatePickerComponent, FastNumericTextBoxComponent, FastUploadComponent, FastToggleComponent, FastGridColComponent, FastGridDateFilterCell, FastListviewComponent, FastTextAreaComponent, FastTreeviewComponent, FastContextMenuComponent, FastCheckboxComponent, FastAutocompleteComponent, FastButtonGroupComponent, FastTabGroupComponent, FastTabHeaderComponent, FastTabPanelComponent, FastPanelbarComponent, FastPanelbarItemComponent, FastSVGComponent] as const;
