// Super Admin Dashboard Utilities

import { makeAuthenticatedRequest } from './api-client';
import type { 
  PlatformMetrics, 
  SuperAdminApiResponse, 
  ExportData, 
  ExportType,
  FilterOptions 
} from './super-admin-types';

/**
 * Check if user has super admin privileges
 */
export async function checkSuperAdminAuth(): Promise<any | null> {
  try {
    const result = await makeAuthenticatedRequest('/api/admin/check-super-admin');
    if (result.success && result.data.isSuperAdmin) {
      return result.data;
    }
    return null;
  } catch (error) {

    return null;
  }
}

/**
 * Load platform-wide metrics
 */
export async function loadPlatformMetrics(): Promise<PlatformMetrics | null> {
  try {
    const result = await makeAuthenticatedRequest('/api/admin/super-analytics?metric=platform_overview');
    
    if (result.success) {
      const data = result.data.summary;
      return {
        totalRevenue: data.totalRevenue || 0,
        totalFees: data.totalPlatformFees || 0,
        activeOrganizers: data.activeOrganizers || 0,
        totalTickets: data.totalTickets || 0,
        revenueChange: data.revenueGrowth || 0,
        feesChange: data.feesGrowth || 0,
        organizersChange: data.organizersThisMonth || 0,
        ticketsChange: data.ticketsThisMonth || 0
      };
    }
    return null;
  } catch (error) {

    return null;
  }
}

/**
 * Generic function to load super admin analytics
 */
export async function loadSuperAdminData<T>(
  metric: string, 
  options: FilterOptions = {}
): Promise<SuperAdminApiResponse<T>> {
  try {
    const params = new URLSearchParams({ metric });
    
    // Add filter options to params
    Object.entries(options).forEach(([key, value]) => {
      if (value !== undefined && value !== null && value !== '') {
        params.append(key, value.toString());
      }
    });
    
    const result = await makeAuthenticatedRequest(`/api/admin/super-analytics?${params}`);
    return result;
  } catch (error) {

    return {
      success: false,
      data: {} as T,
      error: error instanceof Error ? error.message : 'Unknown error'
    };
  }
}

/**
 * Format currency values consistently
 */
export function formatCurrency(amount: number): string {
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
    minimumFractionDigits: 0,
    maximumFractionDigits: 2
  }).format(amount);
}

/**
 * Format percentage values
 */
export function formatPercentage(value: number, decimals: number = 1): string {
  return `${value.toFixed(decimals)}%`;
}

/**
 * Format large numbers with appropriate suffixes
 */
export function formatNumber(num: number): string {
  if (num >= 1000000) {
    return (num / 1000000).toFixed(1) + 'M';
  }
  if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'K';
  }
  return num.toString();
}

/**
 * Get relative time string (e.g., "2 days ago")
 */
export function getRelativeTime(date: string | Date): string {
  const now = new Date();
  const past = new Date(date);
  const diffInMs = now.getTime() - past.getTime();
  const diffInDays = Math.floor(diffInMs / (1000 * 60 * 60 * 24));
  
  if (diffInDays === 0) return 'Today';
  if (diffInDays === 1) return 'Yesterday';
  if (diffInDays < 7) return `${diffInDays} days ago`;
  if (diffInDays < 30) return `${Math.floor(diffInDays / 7)} weeks ago`;
  if (diffInDays < 365) return `${Math.floor(diffInDays / 30)} months ago`;
  return `${Math.floor(diffInDays / 365)} years ago`;
}

/**
 * Convert data to CSV format
 */
export function convertToCSV(data: ExportData[]): string {
  if (!data.length) return '';
  
  const headers = Object.keys(data[0]).join(',');
  const rows = data.map(row => 
    Object.values(row).map(value => 
      typeof value === 'string' ? `"${value.replace(/"/g, '""')}"` : value
    ).join(',')
  );
  
  return [headers, ...rows].join('\n');
}

/**
 * Download CSV file
 */
export function downloadCSV(csvContent: string, filename: string): void {
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  
  link.href = url;
  link.download = filename;
  link.style.display = 'none';
  
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  
  URL.revokeObjectURL(url);
}

/**
 * Export data with loading state management
 */
export async function exportData(
  type: ExportType,
  setLoading: (loading: boolean) => void,
  options: FilterOptions = {}
): Promise<void> {
  setLoading(true);
  
  try {
    let data: ExportData[] = [];
    let filename = '';
    
    switch (type) {
      case 'revenue': {
        const revenueResult = await loadSuperAdminData('revenue_breakdown', options);
        if (revenueResult.success) {
          const totals = revenueResult.data.totals || {};
          const processingFees = (totals.grossRevenue || 0) * 0.029;
          data = [{
            gross_revenue: totals.grossRevenue || 0,
            platform_fees: totals.platformFees || 0,
            processing_fees: processingFees,
            net_to_organizers: (totals.grossRevenue || 0) - (totals.platformFees || 0) - processingFees,
            export_date: new Date().toISOString()
          }];
        }
        filename = `revenue-report-${new Date().toISOString().split('T')[0]}.csv`;
        break;
      }
        
      case 'organizers': {
        const organizerResult = await loadSuperAdminData('organizer_performance', options);
        if (organizerResult.success) {
          data = (organizerResult.data.organizers || []).map((org: any) => ({
            name: org.name,
            email: org.email || '',
            events: org.eventCount || 0,
            published_events: org.publishedEvents || 0,
            tickets_sold: org.ticketsSold || 0,
            total_revenue: org.totalRevenue || 0,
            platform_fees: org.platformFees || 0,
            avg_ticket_price: org.avgTicketPrice || 0,
            join_date: org.joinDate || ''
          }));
        }
        filename = `organizers-${new Date().toISOString().split('T')[0]}.csv`;
        break;
      }
        
      case 'events': {
        const eventResult = await loadSuperAdminData('event_analytics', options);
        if (eventResult.success) {
          data = (eventResult.data.events || []).map((event: any) => ({
            title: event.title,
            organization_id: event.organizationId,
            organizer_name: event.organizerName || '',
            start_time: event.startTime,
            is_published: event.isPublished,
            category: event.category || '',
            tickets_sold: event.ticketsSold || 0,
            total_revenue: event.totalRevenue || 0,
            sell_through_rate: event.sellThroughRate || 0,
            avg_ticket_price: event.avgTicketPrice || 0
          }));
        }
        filename = `events-${new Date().toISOString().split('T')[0]}.csv`;
        break;
      }
        
      case 'tickets': {
        const ticketResult = await loadSuperAdminData('ticket_analytics', { ...options, export: 'true' });
        if (ticketResult.success) {
          data = (ticketResult.data.tickets || []).map((ticket: any) => ({
            ticket_id: ticket.id,
            customer_name: ticket.customerName || '',
            customer_email: ticket.customerEmail || '',
            event_title: ticket.event?.title || '',
            organizer_name: ticket.event?.organizationName || '',
            ticket_type: ticket.ticketType?.name || 'General',
            price: ticket.price || 0,
            seat: ticket.seatRow && ticket.seatNumber ? `${ticket.seatRow}-${ticket.seatNumber}` : 'GA',
            status: ticket.status || 'unknown',
            purchase_date: ticket.createdAt || '',
            used_date: ticket.usedAt || '',
            refunded_date: ticket.refundedAt || ''
          }));
        }
        filename = `tickets-${new Date().toISOString().split('T')[0]}.csv`;
        break;
      }
    }
    
    if (data.length > 0) {
      const csvContent = convertToCSV(data);
      downloadCSV(csvContent, filename);
    } else {
      throw new Error('No data available for export');
    }
    
  } catch (error) {

    alert(`Error exporting ${type} data: ${error instanceof Error ? error.message : 'Unknown error'}`);
  } finally {
    setLoading(false);
  }
}

/**
 * Get status color classes for UI elements
 */
export function getStatusColor(status: string): string {
  const statusColors: Record<string, string> = {
    'active': 'bg-green-500/20 text-green-400 border-green-500/30',
    'used': 'bg-blue-500/20 text-blue-400 border-blue-500/30',
    'refunded': 'bg-red-500/20 text-red-400 border-red-500/30',
    'cancelled': 'bg-gray-500/20 text-gray-400 border-gray-500/30',
    'pending': 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30',
    'confirmed': 'bg-green-500/20 text-green-400 border-green-500/30',
    'draft': 'bg-gray-500/20 text-gray-400 border-gray-500/30',
    'published': 'bg-green-500/20 text-green-400 border-green-500/30',
    'past': 'bg-gray-500/20 text-gray-400 border-gray-500/30'
  };
  
  return statusColors[status.toLowerCase()] || 'bg-gray-500/20 text-gray-400 border-gray-500/30';
}

/**
 * Debounce function for search inputs
 */
export function debounce<T extends (...args: any[]) => any>(
  func: T,
  wait: number
): (...args: Parameters<T>) => void {
  let timeout: NodeJS.Timeout;
  
  return (...args: Parameters<T>) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => func(...args), wait);
  };
}