/**
 * Admin Service
 * API client for admin endpoints - models, predictions, agent performance
 */

const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:3081';
const ML_API_URL = import.meta.env.VITE_ML_URL || 'http://localhost:3083';

// ============================================================================
// Types
// ============================================================================

export interface MLModel {
  model_id: string;
  name: string;
  type: 'AMD' | 'ICT' | 'Range' | 'TPSL' | 'Ensemble';
  version: string;
  status: 'active' | 'training' | 'inactive' | 'error';
  accuracy: number;
  precision: number;
  recall: number;
  f1_score: number;
  last_trained: string;
  last_prediction: string;
  total_predictions: number;
  successful_predictions: number;
  metrics: {
    win_rate: number;
    profit_factor: number;
    sharpe_ratio: number;
    max_drawdown: number;
    avg_risk_reward: number;
  };
}

export interface Prediction {
  prediction_id: string;
  model_id: string;
  model_name: string;
  symbol: string;
  direction: 'long' | 'short';
  predicted_price: number;
  actual_price?: number;
  confidence: number;
  created_at: string;
  result?: 'success' | 'failed' | 'pending';
  profit_loss?: number;
  entry_price: number;
  exit_price?: number;
  take_profit: number;
  stop_loss: number;
}

export interface AgentPerformance {
  agent_id: string;
  name: 'Atlas' | 'Orion' | 'Nova';
  description: string;
  status: 'active' | 'paused' | 'stopped';
  total_signals: number;
  successful_signals: number;
  failed_signals: number;
  win_rate: number;
  total_pnl: number;
  total_trades: number;
  avg_profit_per_trade: number;
  best_trade: number;
  worst_trade: number;
  avg_confidence: number;
  sharpe_ratio: number;
  max_drawdown: number;
  last_signal_at: string;
  created_at: string;
  performance_by_symbol: {
    [symbol: string]: {
      trades: number;
      win_rate: number;
      pnl: number;
    };
  };
}

export interface SignalHistory {
  signal_id: string;
  agent_name: string;
  symbol: string;
  direction: 'long' | 'short';
  entry_price: number;
  exit_price?: number;
  stop_loss: number;
  take_profit: number;
  confidence: number;
  status: 'active' | 'completed' | 'stopped';
  result?: 'win' | 'loss' | 'breakeven';
  profit_loss?: number;
  created_at: string;
  closed_at?: string;
}

export interface AdminStats {
  total_models: number;
  active_models: number;
  total_predictions_today: number;
  total_predictions_week: number;
  overall_accuracy: number;
  total_agents: number;
  active_agents: number;
  total_signals_today: number;
  total_pnl_today: number;
  total_pnl_week: number;
  total_pnl_month: number;
  system_health: 'healthy' | 'degraded' | 'down';
}

export interface SystemHealth {
  status: string;
  services: {
    database: { status: string; latency?: number };
    mlEngine: { status: string };
    tradingAgents: { status: string };
    redis?: { status: string };
  };
  system: {
    uptime: number;
    memory: {
      used: number;
      total: number;
      percentage: number;
    };
  };
  timestamp: string;
}

// ============================================================================
// API Functions - ML Models
// ============================================================================

export async function getMLModels(): Promise<MLModel[]> {
  try {
    const response = await fetch(`${ML_API_URL}/models`);
    if (!response.ok) throw new Error(`API error: ${response.status}`);
    return await response.json();
  } catch (error) {
    console.error('Error fetching ML models:', error);
    return [];
  }
}

export async function getMLModel(modelId: string): Promise<MLModel | null> {
  try {
    const response = await fetch(`${ML_API_URL}/models/${modelId}/status`);
    if (!response.ok) {
      if (response.status === 404) return null;
      throw new Error(`API error: ${response.status}`);
    }
    return await response.json();
  } catch (error) {
    console.error('Error fetching ML model:', error);
    return null;
  }
}

export async function updateMLModelStatus(modelId: string, status: 'active' | 'inactive'): Promise<boolean> {
  try {
    const response = await fetch(`${ML_API_URL}/models/${modelId}/status`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ status }),
    });
    return response.ok;
  } catch (error) {
    console.error('Error updating model status:', error);
    return false;
  }
}

// ============================================================================
// API Functions - Predictions
// ============================================================================

export async function getPredictions(params?: {
  model_id?: string;
  symbol?: string;
  start_date?: string;
  end_date?: string;
  result?: 'success' | 'failed' | 'pending';
  limit?: number;
}): Promise<Prediction[]> {
  try {
    const queryParams = new URLSearchParams();
    if (params?.model_id) queryParams.append('model_id', params.model_id);
    if (params?.symbol) queryParams.append('symbol', params.symbol);
    if (params?.start_date) queryParams.append('start_date', params.start_date);
    if (params?.end_date) queryParams.append('end_date', params.end_date);
    if (params?.result) queryParams.append('result', params.result);
    if (params?.limit) queryParams.append('limit', params.limit.toString());

    const response = await fetch(`${API_URL}/api/v1/ml/predictions?${queryParams.toString()}`);
    if (!response.ok) throw new Error(`API error: ${response.status}`);
    const data = await response.json();
    return data.data || [];
  } catch (error) {
    console.error('Error fetching predictions:', error);
    return [];
  }
}

// ============================================================================
// API Functions - Agents
// ============================================================================

export async function getAgents(): Promise<AgentPerformance[]> {
  try {
    const response = await fetch(`${API_URL}/api/v1/agents`);
    if (!response.ok) throw new Error(`API error: ${response.status}`);
    const data = await response.json();
    return data.data || [];
  } catch (error) {
    console.error('Error fetching agents:', error);
    return [];
  }
}

export async function getAgent(agentId: string): Promise<AgentPerformance | null> {
  try {
    const response = await fetch(`${API_URL}/api/v1/agents/${agentId}`);
    if (!response.ok) {
      if (response.status === 404) return null;
      throw new Error(`API error: ${response.status}`);
    }
    const data = await response.json();
    return data.data;
  } catch (error) {
    console.error('Error fetching agent:', error);
    return null;
  }
}

export async function updateAgentStatus(agentId: string, status: 'active' | 'paused' | 'stopped'): Promise<boolean> {
  try {
    const response = await fetch(`${API_URL}/api/v1/agents/${agentId}/status`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ status }),
    });
    return response.ok;
  } catch (error) {
    console.error('Error updating agent status:', error);
    return false;
  }
}

// ============================================================================
// API Functions - Signals
// ============================================================================

export async function getSignalHistory(params?: {
  agent_id?: string;
  symbol?: string;
  status?: string;
  limit?: number;
}): Promise<SignalHistory[]> {
  try {
    const queryParams = new URLSearchParams();
    if (params?.agent_id) queryParams.append('agent_id', params.agent_id);
    if (params?.symbol) queryParams.append('symbol', params.symbol);
    if (params?.status) queryParams.append('status', params.status);
    if (params?.limit) queryParams.append('limit', params.limit.toString());

    const response = await fetch(`${API_URL}/api/v1/trading/signals?${queryParams.toString()}`);
    if (!response.ok) throw new Error(`API error: ${response.status}`);
    const data = await response.json();
    return data.data || [];
  } catch (error) {
    console.error('Error fetching signal history:', error);
    return [];
  }
}

// ============================================================================
// API Functions - Admin Dashboard
// ============================================================================

export async function getAdminDashboard(): Promise<AdminStats | null> {
  try {
    const response = await fetch(`${API_URL}/api/v1/admin/dashboard`);
    if (!response.ok) throw new Error(`API error: ${response.status}`);
    const data = await response.json();
    return data.data;
  } catch (error) {
    console.error('Error fetching admin dashboard:', error);
    return null;
  }
}

export async function getSystemHealth(): Promise<SystemHealth | null> {
  try {
    const response = await fetch(`${API_URL}/api/v1/admin/system/health`);
    if (!response.ok) throw new Error(`API error: ${response.status}`);
    const data = await response.json();
    return data.data;
  } catch (error) {
    console.error('Error fetching system health:', error);
    return null;
  }
}

// ============================================================================
// API Functions - Users Management
// ============================================================================

export interface User {
  id: string;
  email: string;
  role: 'user' | 'premium' | 'admin';
  status: 'active' | 'suspended' | 'banned';
  created_at: string;
  full_name?: string;
  avatar_url?: string;
}

export async function getUsers(params?: {
  page?: number;
  limit?: number;
  status?: string;
  role?: string;
  search?: string;
}): Promise<{ users: User[]; total: number; page: number; totalPages: number }> {
  try {
    const queryParams = new URLSearchParams();
    if (params?.page) queryParams.append('page', params.page.toString());
    if (params?.limit) queryParams.append('limit', params.limit.toString());
    if (params?.status) queryParams.append('status', params.status);
    if (params?.role) queryParams.append('role', params.role);
    if (params?.search) queryParams.append('search', params.search);

    const response = await fetch(`${API_URL}/api/v1/admin/users?${queryParams.toString()}`);
    if (!response.ok) throw new Error(`API error: ${response.status}`);
    const data = await response.json();
    return {
      users: data.data || [],
      total: data.meta?.total || 0,
      page: data.meta?.page || 1,
      totalPages: data.meta?.totalPages || 1,
    };
  } catch (error) {
    console.error('Error fetching users:', error);
    return { users: [], total: 0, page: 1, totalPages: 1 };
  }
}

export async function updateUserStatus(userId: string, status: string, reason?: string): Promise<boolean> {
  try {
    const response = await fetch(`${API_URL}/api/v1/admin/users/${userId}/status`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ status, reason }),
    });
    return response.ok;
  } catch (error) {
    console.error('Error updating user status:', error);
    return false;
  }
}

export async function updateUserRole(userId: string, role: string): Promise<boolean> {
  try {
    const response = await fetch(`${API_URL}/api/v1/admin/users/${userId}/role`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ role }),
    });
    return response.ok;
  } catch (error) {
    console.error('Error updating user role:', error);
    return false;
  }
}

// ============================================================================
// API Functions - Audit Logs
// ============================================================================

export interface AuditLog {
  id: string;
  user_id: string;
  action: string;
  resource: string;
  details: Record<string, unknown>;
  ip_address: string;
  created_at: string;
}

export async function getAuditLogs(params?: {
  page?: number;
  limit?: number;
  userId?: string;
  action?: string;
  startDate?: string;
  endDate?: string;
}): Promise<{ logs: AuditLog[]; total: number }> {
  try {
    const queryParams = new URLSearchParams();
    if (params?.page) queryParams.append('page', params.page.toString());
    if (params?.limit) queryParams.append('limit', params.limit.toString());
    if (params?.userId) queryParams.append('userId', params.userId);
    if (params?.action) queryParams.append('action', params.action);
    if (params?.startDate) queryParams.append('startDate', params.startDate);
    if (params?.endDate) queryParams.append('endDate', params.endDate);

    const response = await fetch(`${API_URL}/api/v1/admin/audit/logs?${queryParams.toString()}`);
    if (!response.ok) throw new Error(`API error: ${response.status}`);
    const data = await response.json();
    return {
      logs: data.data || [],
      total: data.meta?.total || 0,
    };
  } catch (error) {
    console.error('Error fetching audit logs:', error);
    return { logs: [], total: 0 };
  }
}
