import { apiClient } from './client'
import type { SportEvent } from '@/types/sport-event'
import type {
  AdminDashboardStats,
  AuditLogListResponse,
  WipePreview,
  WipeRequest,
  WipeResponse,
  SeedRequest,
  SeedResponse,
  SimulationStatus,
  SimulationConfig,
  SimulationStartResponse,
  SimulationStopResponse,
  AdminUserListResponse,
  AdminUserDetail,
  UserUpdateRequest,
  UserStatusRequest,
  BalanceAdjustRequest,
  BalanceAdjustResponse,
} from '@/types/admin'

export interface AdminSettings {
  id: number
  default_house_commission_percent: number
  default_min_bet_amount: number
  default_max_bet_amount: number
  default_min_spread: number
  default_max_spread: number
  spread_increment: number
  platform_name: string
  maintenance_mode: boolean
}

export interface CreateEventData {
  sport: string
  home_team: string
  away_team: string
  official_spread: number
  game_time: string
  venue?: string
  league?: string
  min_spread?: number
  max_spread?: number
  min_bet_amount?: number
  max_bet_amount?: number
}

export const adminApi = {
  // Dashboard
  getDashboard: async (): Promise<AdminDashboardStats> => {
    const response = await apiClient.get<AdminDashboardStats>('/api/v1/admin/dashboard')
    return response.data
  },

  // Settings
  getSettings: async (): Promise<AdminSettings> => {
    const response = await apiClient.get<AdminSettings>('/api/v1/admin/settings')
    return response.data
  },

  updateSettings: async (settings: Partial<AdminSettings>): Promise<AdminSettings> => {
    const response = await apiClient.patch<AdminSettings>('/api/v1/admin/settings', settings)
    return response.data
  },

  // Events
  createEvent: async (eventData: CreateEventData): Promise<SportEvent> => {
    const response = await apiClient.post<SportEvent>('/api/v1/admin/events', eventData)
    return response.data
  },

  getEvents: async (params?: { skip?: number; limit?: number }): Promise<SportEvent[]> => {
    const queryParams = new URLSearchParams()
    if (params?.skip !== undefined) queryParams.append('skip', params.skip.toString())
    if (params?.limit !== undefined) queryParams.append('limit', params.limit.toString())

    const url = `/api/v1/admin/events${queryParams.toString() ? `?${queryParams}` : ''}`
    const response = await apiClient.get<SportEvent[]>(url)
    return response.data
  },

  deleteEvent: async (eventId: number): Promise<{ message: string }> => {
    const response = await apiClient.delete<{ message: string }>(`/api/v1/admin/events/${eventId}`)
    return response.data
  },

  // Audit Logs
  getAuditLogs: async (params?: {
    page?: number
    page_size?: number
    action?: string
    admin_id?: number
    target_type?: string
  }): Promise<AuditLogListResponse> => {
    const queryParams = new URLSearchParams()
    if (params?.page) queryParams.append('page', params.page.toString())
    if (params?.page_size) queryParams.append('page_size', params.page_size.toString())
    if (params?.action) queryParams.append('action', params.action)
    if (params?.admin_id) queryParams.append('admin_id', params.admin_id.toString())
    if (params?.target_type) queryParams.append('target_type', params.target_type)

    const url = `/api/v1/admin/audit-logs${queryParams.toString() ? `?${queryParams}` : ''}`
    const response = await apiClient.get<AuditLogListResponse>(url)
    return response.data
  },

  // Data Wiper
  getWipePreview: async (): Promise<WipePreview> => {
    const response = await apiClient.get<WipePreview>('/api/v1/admin/data/wipe/preview')
    return response.data
  },

  executeWipe: async (request: WipeRequest): Promise<WipeResponse> => {
    const response = await apiClient.post<WipeResponse>('/api/v1/admin/data/wipe', request)
    return response.data
  },

  // Data Seeder
  seedDatabase: async (request: SeedRequest): Promise<SeedResponse> => {
    const response = await apiClient.post<SeedResponse>('/api/v1/admin/data/seed', request)
    return response.data
  },

  // Simulation
  getSimulationStatus: async (): Promise<SimulationStatus> => {
    const response = await apiClient.get<SimulationStatus>('/api/v1/admin/simulation/status')
    return response.data
  },

  startSimulation: async (config?: SimulationConfig): Promise<SimulationStartResponse> => {
    const response = await apiClient.post<SimulationStartResponse>('/api/v1/admin/simulation/start', {
      config,
    })
    return response.data
  },

  stopSimulation: async (): Promise<SimulationStopResponse> => {
    const response = await apiClient.post<SimulationStopResponse>('/api/v1/admin/simulation/stop')
    return response.data
  },

  // User Management
  getUsers: async (params?: {
    page?: number
    page_size?: number
    search?: string
    status_filter?: string
    is_admin?: boolean
  }): Promise<AdminUserListResponse> => {
    const queryParams = new URLSearchParams()
    if (params?.page) queryParams.append('page', params.page.toString())
    if (params?.page_size) queryParams.append('page_size', params.page_size.toString())
    if (params?.search) queryParams.append('search', params.search)
    if (params?.status_filter) queryParams.append('status_filter', params.status_filter)
    if (params?.is_admin !== undefined) queryParams.append('is_admin', params.is_admin.toString())

    const url = `/api/v1/admin/users${queryParams.toString() ? `?${queryParams}` : ''}`
    const response = await apiClient.get<AdminUserListResponse>(url)
    return response.data
  },

  getUser: async (userId: number): Promise<AdminUserDetail> => {
    const response = await apiClient.get<AdminUserDetail>(`/api/v1/admin/users/${userId}`)
    return response.data
  },

  updateUser: async (
    userId: number,
    data: UserUpdateRequest
  ): Promise<{ message: string; changes: Record<string, unknown> }> => {
    const response = await apiClient.patch<{ message: string; changes: Record<string, unknown> }>(
      `/api/v1/admin/users/${userId}`,
      data
    )
    return response.data
  },

  changeUserStatus: async (userId: number, data: UserStatusRequest): Promise<{ message: string }> => {
    const response = await apiClient.patch<{ message: string }>(
      `/api/v1/admin/users/${userId}/status`,
      data
    )
    return response.data
  },

  adjustUserBalance: async (userId: number, data: BalanceAdjustRequest): Promise<BalanceAdjustResponse> => {
    const response = await apiClient.post<BalanceAdjustResponse>(
      `/api/v1/admin/users/${userId}/balance`,
      data
    )
    return response.data
  },
}
