import * as plugins from './plugins.js';
import * as appstate from './appstate.js';

const SmartRouter = plugins.domtools.plugins.smartrouter.SmartRouter;

export const validViews = ['overview', 'network', 'emails', 'logs', 'routes', 'apitokens', 'configuration', 'security', 'certificates', 'remoteingress', 'vpn', 'securityprofiles', 'networktargets'] as const;

export type TValidView = typeof validViews[number];

class AppRouter {
  private router: InstanceType<typeof SmartRouter>;
  private initialized = false;
  private suppressStateUpdate = false;

  constructor() {
    this.router = new SmartRouter({ debug: false });
  }

  public init(): void {
    if (this.initialized) return;
    this.setupRoutes();
    this.setupStateSync();
    this.handleInitialRoute();
    this.initialized = true;
  }

  private setupRoutes(): void {
    for (const view of validViews) {
      this.router.on(`/${view}`, async () => {
        this.updateViewState(view);
      });
    }

    // Root redirect
    this.router.on('/', async () => {
      this.navigateTo('/overview');
    });
  }

  private setupStateSync(): void {
    appstate.uiStatePart.select().subscribe((uiState) => {
      if (this.suppressStateUpdate) return;

      const currentPath = window.location.pathname;
      const expectedPath = `/${uiState.activeView}`;

      if (currentPath !== expectedPath) {
        this.suppressStateUpdate = true;
        this.router.pushUrl(expectedPath);
        this.suppressStateUpdate = false;
      }
    });
  }

  private handleInitialRoute(): void {
    const path = window.location.pathname;

    if (!path || path === '/') {
      this.router.pushUrl('/overview');
    } else {
      const segments = path.split('/').filter(Boolean);
      const view = segments[0];

      if (validViews.includes(view as TValidView)) {
        this.updateViewState(view as TValidView);
      } else {
        this.router.pushUrl('/overview');
      }
    }
  }

  private updateViewState(view: string): void {
    this.suppressStateUpdate = true;
    const currentState = appstate.uiStatePart.getState()!;
    if (currentState.activeView !== view) {
      appstate.uiStatePart.setState({
        ...currentState,
        activeView: view,
      } as appstate.IUiState);
    }
    this.suppressStateUpdate = false;
  }

  public navigateTo(path: string): void {
    this.router.pushUrl(path);
  }

  public navigateToView(view: string): void {
    if (validViews.includes(view as TValidView)) {
      this.navigateTo(`/${view}`);
    } else {
      this.navigateTo('/overview');
    }
  }

  public getCurrentView(): string {
    return appstate.uiStatePart.getState()!.activeView;
  }

  public destroy(): void {
    this.router.destroy();
    this.initialized = false;
  }
}

export const appRouter = new AppRouter();
