import client from './client'
import type {
  AdminUser,
  AdminMarathon,
  UserRole,
  PlatformStats,
  AdminLogsResponse,
  BroadcastResponse,
  StaticContent,
  DashboardStats,
  AdminDispute
} from '@/types'

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

  // Users
  listUsers: async (skip = 0, limit = 50, search?: string, bannedOnly = false): Promise<AdminUser[]> => {
    const params: Record<string, unknown> = { skip, limit, banned_only: bannedOnly }
    if (search) params.search = search
    const response = await client.get<AdminUser[]>('/admin/users', { params })
    return response.data
  },

  getUser: async (id: number): Promise<AdminUser> => {
    const response = await client.get<AdminUser>(`/admin/users/${id}`)
    return response.data
  },

  setUserRole: async (id: number, role: UserRole): Promise<AdminUser> => {
    const response = await client.patch<AdminUser>(`/admin/users/${id}/role`, { role })
    return response.data
  },

  deleteUser: async (id: number): Promise<void> => {
    await client.delete(`/admin/users/${id}`)
  },

  banUser: async (id: number, reason: string, bannedUntil?: string): Promise<AdminUser> => {
    const response = await client.post<AdminUser>(`/admin/users/${id}/ban`, {
      reason,
      banned_until: bannedUntil || null,
    })
    return response.data
  },

  unbanUser: async (id: number): Promise<AdminUser> => {
    const response = await client.post<AdminUser>(`/admin/users/${id}/unban`)
    return response.data
  },

  resetUserPassword: async (id: number, newPassword: string): Promise<AdminUser> => {
    const response = await client.post<AdminUser>(`/admin/users/${id}/reset-password`, {
      new_password: newPassword,
    })
    return response.data
  },

  // Marathons
  listMarathons: async (skip = 0, limit = 50, search?: string): Promise<AdminMarathon[]> => {
    const params: Record<string, unknown> = { skip, limit }
    if (search) params.search = search
    const response = await client.get<AdminMarathon[]>('/admin/marathons', { params })
    return response.data
  },

  deleteMarathon: async (id: number): Promise<void> => {
    await client.delete(`/admin/marathons/${id}`)
  },

  forceFinishMarathon: async (id: number): Promise<void> => {
    await client.post(`/admin/marathons/${id}/force-finish`)
  },

  certifyMarathon: async (id: number): Promise<void> => {
    await client.post(`/admin/marathons/${id}/certify`)
  },

  revokeCertification: async (id: number): Promise<void> => {
    await client.post(`/admin/marathons/${id}/revoke-certification`)
  },

  // Stats
  getStats: async (): Promise<PlatformStats> => {
    const response = await client.get<PlatformStats>('/admin/stats')
    return response.data
  },

  // Logs
  getLogs: async (skip = 0, limit = 50, action?: string, adminId?: number): Promise<AdminLogsResponse> => {
    const params: Record<string, unknown> = { skip, limit }
    if (action) params.action = action
    if (adminId) params.admin_id = adminId
    const response = await client.get<AdminLogsResponse>('/admin/logs', { params })
    return response.data
  },

  // Broadcast
  broadcastToAll: async (message: string, media?: File[]): Promise<BroadcastResponse> => {
    const formData = new FormData()
    formData.append('message', message)
    if (media && media.length > 0) {
      media.forEach(file => {
        formData.append('media', file)
      })
    }
    const response = await client.post<BroadcastResponse>('/admin/broadcast/all', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    return response.data
  },

  broadcastToMarathon: async (marathonId: number, message: string, media?: File[]): Promise<BroadcastResponse> => {
    const formData = new FormData()
    formData.append('message', message)
    if (media && media.length > 0) {
      media.forEach(file => {
        formData.append('media', file)
      })
    }
    const response = await client.post<BroadcastResponse>(`/admin/broadcast/marathon/${marathonId}`, formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    return response.data
  },

  // Static Content
  listContent: async (): Promise<StaticContent[]> => {
    const response = await client.get<StaticContent[]>('/admin/content')
    return response.data
  },

  getContent: async (key: string): Promise<StaticContent> => {
    const response = await client.get<StaticContent>(`/admin/content/${key}`)
    return response.data
  },

  updateContent: async (key: string, title: string, content: string): Promise<StaticContent> => {
    const response = await client.put<StaticContent>(`/admin/content/${key}`, { title, content })
    return response.data
  },

  createContent: async (key: string, title: string, content: string): Promise<StaticContent> => {
    const response = await client.post<StaticContent>('/admin/content', { key, title, content })
    return response.data
  },

  deleteContent: async (key: string): Promise<void> => {
    await client.delete(`/admin/content/${key}`)
  },

  // Disputes
  listDisputes: async (status: 'pending' | 'open' | 'all' = 'pending'): Promise<AdminDispute[]> => {
    const response = await client.get<AdminDispute[]>('/admin/disputes', { params: { status } })
    return response.data
  },

  resolveDispute: async (disputeId: number, isValid: boolean): Promise<{ message: string }> => {
    const response = await client.post<{ message: string }>(`/admin/disputes/${disputeId}/resolve`, {
      is_valid: isValid,
    })
    return response.data
  },
}

// Public content API (no auth required)
export const contentApi = {
  getPublicContent: async (key: string): Promise<StaticContent> => {
    const response = await client.get<StaticContent>(`/content/${key}`)
    return response.data
  },
}
