import { apiClient } from './api-client';
import type { EventStats, EventDetails } from './api-client';
import type { EventData } from './event-management';

/**
 * Browser-friendly API router that handles all the common API calls
 * This is designed to be used in Astro client-side scripts and React components
 */
export class ApiRouter {
  
  /**
   * Load event details and statistics for the event management page
   */
  static async loadEventPage(eventId: string): Promise<{
    event: EventDetails | null;
    stats: EventStats | null;
    error: string | null;
  }> {
    try {
      // Initialize API client
      const client = await import('./api-client').then(m => m.useApi());

      // Load event details and stats in parallel
      const [eventResult, statsResult] = await Promise.all([
        client.getEventDetails(eventId),
        client.getEventStats(eventId)
      ]);

      return {
        event: eventResult.data,
        stats: statsResult.data,
        error: eventResult.error || statsResult.error
      };
    } catch (error) {
      console.error('Event page loading error:', error);
      return {
        event: null,
        stats: null,
        error: 'Failed to load event data'
      };
    }
  }

  /**
   * Load only event statistics (for QuickStats component)
   */
  static async loadEventStats(eventId: string): Promise<EventStats | null> {
    try {
      const client = await import('./api-client').then(m => m.useApi());
      
      const result = await client.getEventStats(eventId);
      if (!result.success) {

        return null;
      }
      
      return result.data;
    } catch (error) {

      return null;
    }
  }

  /**
   * Load only event details (for EventHeader component)
   */
  static async loadEventDetails(eventId: string): Promise<EventDetails | null> {
    try {
      const client = await import('./api-client').then(m => m.useApi());
      
      const result = await client.getEventDetails(eventId);
      if (!result.success) {

        return null;
      }
      
      return result.data;
    } catch (error) {

      return null;
    }
  }

  /**
   * Load ticket types for an event
   */
  static async loadTicketTypes(eventId: string): Promise<any[]> {
    try {
      const client = await import('./api-client').then(m => m.useApi());
      
      const result = await client.getTicketTypes(eventId);
      if (!result.success) {

        return [];
      }
      
      return result.data || [];
    } catch (error) {

      return [];
    }
  }

  /**
   * Load orders for an event
   */
  static async loadOrders(eventId: string): Promise<any[]> {
    try {
      const client = await import('./api-client').then(m => m.useApi());
      
      const result = await client.getOrders(eventId);
      if (!result.success) {

        return [];
      }
      
      return result.data || [];
    } catch (error) {

      return [];
    }
  }

  /**
   * Utility method to format currency
   */
  static formatCurrency(amount: number): string {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD'
    }).format(amount / 100);
  }

  /**
   * Utility method to format date
   */
  static formatDate(dateString: string): string {
    return new Date(dateString).toLocaleDateString('en-US', {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      hour: 'numeric',
      minute: '2-digit'
    });
  }

  /**
   * Load complete event data (for EventManagement component)
   * This consolidates the loadEventData function into the API router
   */
  static async loadEventData(eventId: string): Promise<EventData | null> {
    try {
      const { loadEventData } = await import('./event-management');
      const client = await import('./api-client').then(m => m.useApi());
      
      // Get user's organization ID from the API client
      const userOrganizationId = await client.getUserOrganizationId();
      if (!userOrganizationId) {

        return null;
      }
      
      return await loadEventData(eventId, userOrganizationId);
    } catch (error) {

      return null;
    }
  }

  /**
   * Check authentication status
   */
  static async checkAuth(): Promise<{
    authenticated: boolean;
    user: any;
    organizationId: string | null;
  }> {
    try {
      const client = await import('./api-client').then(m => m.useApi());
      
      // The useApi function already initializes if needed, but let's double-check
      // by calling initialize again to ensure we have the latest session state
      await client.initialize();
      
      const isAuthenticated = client.isAuthenticated();
      const user = client.getUser();
      const organizationId = client.getUserOrganizationId();

      return {
        authenticated: isAuthenticated,
        user,
        organizationId
      };
    } catch (error) {

      return {
        authenticated: false,
        user: null,
        organizationId: null
      };
    }
  }

  /**
   * Load presale codes for an event
   */
  static async loadPresaleCodes(eventId: string): Promise<any[]> {
    try {
      const client = await import('./api-client').then(m => m.useApi());
      
      const result = await client.getPresaleCodes(eventId);
      if (!result.success) {

        return [];
      }
      
      return result.data || [];
    } catch (error) {

      return [];
    }
  }

  /**
   * Load discount codes for an event
   */
  static async loadDiscountCodes(eventId: string): Promise<any[]> {
    try {
      const client = await import('./api-client').then(m => m.useApi());
      
      const result = await client.getDiscountCodes(eventId);
      if (!result.success) {

        return [];
      }
      
      return result.data || [];
    } catch (error) {

      return [];
    }
  }

  /**
   * Load attendees for an event
   */
  static async loadAttendees(eventId: string): Promise<any[]> {
    try {
      const client = await import('./api-client').then(m => m.useApi());
      
      const result = await client.getAttendees(eventId);
      if (!result.success) {

        return [];
      }
      
      return result.data || [];
    } catch (error) {

      return [];
    }
  }

  /**
   * Territory Manager integration
   */
  static async isTerritoryManager(): Promise<boolean> {
    try {
      const { TerritoryManagerAuth } = await import('./territory-manager-auth');
      return await TerritoryManagerAuth.isTerritoryManager();
    } catch (error) {

      return false;
    }
  }

  static async getTerritoryManagerRouter() {
    try {
      const { territoryManagerRouter } = await import('./territory-manager-router');
      return territoryManagerRouter;
    } catch (error) {

      return null;
    }
  }
}

// Export the router for global use
export const api = ApiRouter;