import { supabase } from './supabase';

/**
 * Admin API Router for centralized admin dashboard API calls
 * This provides a centralized way to handle admin-specific API operations
 */
export class AdminApiRouter {
  private session: any = null;
  private isAdmin = false;

  /**
   * Initialize the admin API router with authentication
   */
  async initialize(): Promise<boolean> {
    try {
      // Use the admin auth check API instead of client-side Supabase
      const response = await fetch('/api/admin/auth-check', {
        method: 'GET',
        credentials: 'include'
      });

      if (!response.ok) {
        console.error('Admin auth check failed:', response.status);
        return false;
      }

      const result = await response.json();

      if (!result.authenticated || !result.isAdmin) {
        console.error('User not authenticated or not admin:', result);
        return false;
      }

      // Store user info for later use
      this.session = {
        user: result.user
      };
      this.isAdmin = true;

      return true;
    } catch (error) {
      console.error('Admin initialization error:', error);
      return false;
    }
  }

  /**
   * Get platform statistics for admin dashboard
   */
  async getPlatformStats(): Promise<{
    organizations: number;
    events: number;
    tickets: number;
    revenue: number;
    platformFees: number;
    users: number;
    error?: string;
  }> {
    try {
      if (!this.isAdmin) {
        const initialized = await this.initialize();
        if (!initialized) {
          return { organizations: 0, events: 0, tickets: 0, revenue: 0, platformFees: 0, users: 0, error: 'Admin authentication required' };
        }
      }

      const [organizationsResult, eventsResult, ticketsResult] = await Promise.all([
        supabase.from('organizations').select('id'),
        supabase.from('events').select('id'),
        supabase.from('tickets').select('price')
      ]);

      // Get user count from API endpoint to bypass RLS
      let users = 0;
      try {
        const usersResponse = await fetch('/api/admin/users', {
          method: 'GET',
          credentials: 'include'
        });
        if (usersResponse.ok) {
          const usersResult = await usersResponse.json();
          if (usersResult.success) {
            users = usersResult.data?.length || 0;
          }
        }
      } catch (error) {
        console.error('Error fetching user count for stats:', error);
      }

      const organizations = organizationsResult.data?.length || 0;
      const events = eventsResult.data?.length || 0;
      const tickets = ticketsResult.data || [];
      const ticketCount = tickets.length;
      const revenue = tickets.reduce((sum, ticket) => sum + (ticket.price || 0), 0);
      const platformFees = revenue * 0.05; // Assuming 5% platform fee

      return {
        organizations,
        events,
        tickets: ticketCount,
        revenue,
        platformFees,
        users
      };
    } catch (error) {

      return { organizations: 0, events: 0, tickets: 0, revenue: 0, platformFees: 0, users: 0, error: 'Failed to load platform statistics' };
    }
  }

  /**
   * Get recent activity for admin dashboard
   */
  async getRecentActivity(): Promise<any[]> {
    try {
      if (!this.isAdmin) {
        const initialized = await this.initialize();
        if (!initialized) {
          return [];
        }
      }

      const [eventsResult, ticketsResult] = await Promise.all([
        supabase.from('events').select('*, organizations(name)').order('created_at', { ascending: false }).limit(5),
        supabase.from('tickets').select('*, events(title)').order('created_at', { ascending: false }).limit(10)
      ]);

      // Get recent users from API endpoint to bypass RLS
      let usersResult = { data: [] };
      try {
        const usersResponse = await fetch('/api/admin/users', {
          method: 'GET',
          credentials: 'include'
        });
        if (usersResponse.ok) {
          const result = await usersResponse.json();
          if (result.success) {
            // Limit to 5 most recent users
            usersResult.data = result.data.slice(0, 5);
          }
        }
      } catch (error) {
        console.error('Error fetching users for recent activity:', error);
      }

      const activities = [];

      // Add recent events
      if (eventsResult.data) {
        eventsResult.data.forEach(event => {
          activities.push({
            type: 'event',
            title: `New event created: ${event.title}`,
            subtitle: `by ${event.organizations?.name || 'Unknown'}`,
            time: new Date(event.created_at),
            icon: '📅'
          });
        });
      }

      // Add recent users
      if (usersResult.data) {
        usersResult.data.forEach(user => {
          activities.push({
            type: 'user',
            title: `New user registered: ${user.name || user.email}`,
            subtitle: `Organization: ${user.organizations?.name || 'None'}`,
            time: new Date(user.created_at),
            icon: '👤'
          });
        });
      }

      // Add recent tickets
      if (ticketsResult.data) {
        ticketsResult.data.slice(0, 5).forEach(ticket => {
          activities.push({
            type: 'ticket',
            title: `Ticket sold: $${ticket.price}`,
            subtitle: `for ${ticket.events?.title || 'Unknown Event'}`,
            time: new Date(ticket.created_at),
            icon: '🎫'
          });
        });
      }

      // Sort by time and take the most recent 10
      activities.sort((a, b) => b.time - a.time);
      return activities.slice(0, 10);
    } catch (error) {

      return [];
    }
  }

  /**
   * Get a single organization by ID
   */
  async getOrganization(orgId: string): Promise<any | null> {
    try {
      if (!this.isAdmin) {
        const initialized = await this.initialize();
        if (!initialized) {
          return null;
        }
      }

      const { data: org, error } = await supabase
        .from('organizations')
        .select('*')
        .eq('id', orgId)
        .single();

      if (error) {

        return null;
      }

      return org;
    } catch (error) {

      return null;
    }
  }

  /**
   * Get organizations with additional metadata
   */
  async getOrganizations(): Promise<any[]> {
    try {
      if (!this.isAdmin) {
        const initialized = await this.initialize();
        if (!initialized) {
          return [];
        }
      }

      const { data: orgs, error } = await supabase
        .from('organizations')
        .select('*')
        .order('created_at', { ascending: false });

      if (error) {

        return [];
      }

      // Get user counts for each organization
      if (orgs) {
        for (const org of orgs) {
          const { data: users } = await supabase
            .from('users')
            .select('id')
            .eq('organization_id', org.id);
          org.user_count = users ? users.length : 0;
        }
      }

      return orgs || [];
    } catch (error) {

      return [];
    }
  }

  /**
   * Get users with organization details
   */
  async getUsers(): Promise<any[]> {
    try {
      if (!this.isAdmin) {
        const initialized = await this.initialize();
        if (!initialized) {
          return [];
        }
      }

      // Use server-side API endpoint to bypass RLS restrictions
      const response = await fetch('/api/admin/users', {
        method: 'GET',
        credentials: 'include',
        headers: {
          'Content-Type': 'application/json'
        }
      });

      if (!response.ok) {
        console.error('Failed to fetch users:', response.status, response.statusText);
        return [];
      }

      const result = await response.json();
      
      if (!result.success) {
        console.error('Users API error:', result.error);
        return [];
      }

      return result.data || [];
    } catch (error) {
      console.error('Error fetching users:', error);
      return [];
    }
  }

  /**
   * Get events with organization and user details
   */
  async getEvents(): Promise<any[]> {
    try {
      if (!this.isAdmin) {
        const initialized = await this.initialize();
        if (!initialized) {
          return [];
        }
      }

      const { data: events, error } = await supabase
        .from('events')
        .select(`
          *,
          organizations(name),
          users(name, email),
          venues(name)
        `)
        .order('created_at', { ascending: false });

      if (error) {

        return [];
      }

      // Get ticket type counts for each event
      if (events) {
        for (const event of events) {
          const { data: ticketTypes } = await supabase
            .from('ticket_types')
            .select('id')
            .eq('event_id', event.id);
          event.ticket_type_count = ticketTypes ? ticketTypes.length : 0;
        }
      }

      return events || [];
    } catch (error) {

      return [];
    }
  }

  /**
   * Get tickets with event and organization details
   */
  async getTickets(): Promise<any[]> {
    try {
      if (!this.isAdmin) {
        const initialized = await this.initialize();
        if (!initialized) {
          return [];
        }
      }

      const { data: tickets, error } = await supabase
        .from('tickets')
        .select(`
          *,
          ticket_types (
            name,
            price
          ),
          events (
            title,
            venue,
            start_time,
            organizations (
              name
            )
          )
        `)
        .order('created_at', { ascending: false })
        .limit(100);

      if (error) {

        return [];
      }

      return tickets || [];
    } catch (error) {

      return [];
    }
  }

  /**
   * Update organization platform fees
   */
  async updateOrganizationFees(orgId: string, feeData: {
    platform_fee_type: string;
    platform_fee_percentage?: number;
    platform_fee_fixed?: number;
    platform_fee_model: string;
    platform_fee_notes?: string;
  }): Promise<{ success: boolean; error?: string }> {
    try {
      if (!this.isAdmin) {
        const initialized = await this.initialize();
        if (!initialized) {
          return { success: false, error: 'Admin authentication required' };
        }
      }

      const updateData = {
        platform_fee_type: feeData.platform_fee_type,
        platform_fee_model: feeData.platform_fee_model,
        absorb_fee_in_price: feeData.platform_fee_model === 'absorbed_in_price',
        platform_fee_notes: feeData.platform_fee_notes || null
      };

      // Only set fields that should be used based on fee type
      switch (feeData.platform_fee_type) {
        case 'percentage_only':
          updateData.platform_fee_percentage = feeData.platform_fee_percentage || 0;
          updateData.platform_fee_fixed = 0;
          break;
        case 'fixed_only':
          updateData.platform_fee_percentage = 0;
          updateData.platform_fee_fixed = feeData.platform_fee_fixed || 0;
          break;
        case 'percentage_plus_fixed':
        default:
          updateData.platform_fee_percentage = feeData.platform_fee_percentage || 0;
          updateData.platform_fee_fixed = feeData.platform_fee_fixed || 0;
          break;
      }

      const { error } = await supabase
        .from('organizations')
        .update(updateData)
        .eq('id', orgId);

      if (error) {

        return { success: false, error: error.message };
      }

      return { success: true };
    } catch (error) {

      return { success: false, error: 'Failed to update organization fees' };
    }
  }

  /**
   * Create a test event for demonstration
   */
  async createTestEvent(): Promise<{ success: boolean; error?: string; eventId?: string }> {
    try {
      if (!this.isAdmin) {
        const initialized = await this.initialize();
        if (!initialized) {
          return { success: false, error: 'Admin authentication required' };
        }
      }

      // Create a test organization first if none exists
      let testOrgId;
      const { data: orgs } = await supabase.from('organizations').select('id').limit(1);
      
      if (!orgs || orgs.length === 0) {
        const { data: newOrg, error: orgError } = await supabase
          .from('organizations')
          .insert({
            name: 'Demo Organization',
            website: 'https://demo.blackcanyontickets.com',
            description: 'Test organization for platform demonstration'
          })
          .select()
          .single();
        
        if (orgError) {

          return { success: false, error: orgError.message };
        }
        testOrgId = newOrg.id;
      } else {
        testOrgId = orgs[0].id;
      }

      // Create test event
      const { data: event, error } = await supabase
        .from('events')
        .insert({
          title: 'Demo Concert - ' + new Date().toLocaleDateString(),
          slug: 'demo-concert-' + Date.now(),
          description: 'A demonstration event showcasing the Black Canyon Tickets platform features.',
          venue: 'Demo Venue',
          start_time: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(), // 30 days from now
          end_time: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000 + 3 * 60 * 60 * 1000).toISOString(), // +3 hours
          organization_id: testOrgId,
          is_published: true
        })
        .select()
        .single();

      if (error) {

        return { success: false, error: error.message };
      }

      // Create sample ticket types
      const ticketTypesResult = await supabase.from('ticket_types').insert([
        {
          event_id: event.id,
          name: 'General Admission',
          price: 25.00,
          quantity_available: 100,
          description: 'Standard entry ticket'
        },
        {
          event_id: event.id,
          name: 'VIP',
          price: 75.00,
          quantity_available: 20,
          description: 'VIP experience with premium benefits'
        }
      ]);

      if (ticketTypesResult.error) {

        // Event created successfully but ticket types failed
        return { success: true, eventId: event.id, error: 'Event created but ticket types failed' };
      }

      return { success: true, eventId: event.id };
    } catch (error) {

      return { success: false, error: 'Failed to create test event' };
    }
  }

  /**
   * Call the super analytics API with proper authentication
   */
  async getSuperAnalytics(metric: string = 'platform_overview'): Promise<any> {
    try {
      if (!this.session) {
        const initialized = await this.initialize();
        if (!initialized) {
          return { success: false, error: 'Authentication required' };
        }
      }

      // Construct full URL to handle localhost issues
      let baseUrl = window.location.origin;
      
      // Special handling for localhost to ensure proper resolution
      if (window.location.hostname === 'localhost' && window.location.port) {
        baseUrl = `${window.location.protocol}//localhost:${window.location.port}`;
      }
      
      const apiUrl = `${baseUrl}/api/admin/super-analytics?metric=${metric}`;

      // Add timeout to prevent hanging
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), 10000); // 10 second timeout
      
      const response = await fetch(apiUrl, {
        headers: {
          'Authorization': `Bearer ${this.session.access_token}`,
          'Content-Type': 'application/json'
        },
        signal: controller.signal
      }).finally(() => clearTimeout(timeoutId));

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      return await response.json();
    } catch (error: any) {

      if (error.name === 'AbortError') {
        return { success: false, error: 'Request timeout - the server took too long to respond' };
      }
      
      return { 
        success: false, 
        error: error.message || 'Failed to load analytics data',
        details: {
          errorType: error.name,
          metric: metric,
          url: window.location.href
        }
      };
    }
  }

  /**
   * Get user information
   */
  getUserInfo(): { name: string; email: string } | null {
    if (!this.session) return null;
    
    return {
      name: this.session.user.user_metadata?.name || this.session.user.email,
      email: this.session.user.email
    };
  }

  /**
   * Check if user is authenticated as admin
   */
  isAuthenticated(): boolean {
    return this.isAdmin && this.session !== null;
  }

  /**
   * Get Supabase client for direct access
   */
  getSupabaseClient() {
    return supabase;
  }

  /**
   * Get current session
   */
  getSession() {
    return this.session;
  }

  /**
   * Sign out
   */
  async signOut(): Promise<void> {
    await supabase.auth.signOut();
    this.session = null;
    this.isAdmin = false;
  }
}

// Export singleton instance
export const adminApi = new AdminApiRouter();