import { apiDelete, apiGet, apiPost, apiPut } from '@/lib/http'
import type {
  UploadedFile,
  WorkCategory,
  WorkOrder,
  WorkOrderShare,
  WorkProductRule,
  WorkerFinanceConfig,
  WorkerFinanceRequest,
  WorkerLevel,
  WorkerListResponse,
  WorkerUser,
} from '@/types/worker-platform'

export function fetchAdminWorkerPlatformSummary() {
  return apiGet<{
    pendingWorkerCount: number
    pendingMaterialCount: number
    openOrderCount: number
    inProgressOrderCount: number
  }>('/api/v1/admin/worker-platform/summary')
}

export function fetchAdminWorkerLevels() {
  return apiGet<{ items: WorkerLevel[] }>(
    '/api/v1/admin/worker-platform/levels',
  )
}

export function fetchAdminWorkCategories() {
  return apiGet<{ items: WorkCategory[] }>(
    '/api/v1/admin/worker-platform/categories',
  )
}

export function saveAdminWorkCategory(payload: {
  categoryKey: string
  name: string
  sortOrder?: number
  status?: string
}) {
  return apiPost<{ category: WorkCategory }>(
    '/api/v1/admin/worker-platform/categories',
    payload,
  )
}

export function deleteAdminWorkCategory(categoryId: number) {
  return apiDelete<{ deleted: boolean }>(
    `/api/v1/admin/worker-platform/categories/${categoryId}`,
  )
}

export function deleteAdminWorkerLevel(levelId: number) {
  return apiDelete<{ deleted: boolean }>(
    `/api/v1/admin/worker-platform/levels/${levelId}`,
  )
}

export function saveAdminWorkerLevel(payload: {
  levelKey: string
  name: string
  depositFreeAmount?: number
  maxActiveOrders?: number
  upgradeThreshold?: number
  visibleDelaySeconds?: number
  status?: string
}) {
  return apiPost<{ level: WorkerLevel }>(
    '/api/v1/admin/worker-platform/levels',
    payload,
  )
}

export function fetchAdminWorkerUsers(params?: Record<string, unknown>) {
  return apiGet<WorkerListResponse<WorkerUser>>(
    '/api/v1/admin/worker-platform/workers',
    params,
  )
}

export function fetchAdminWorkProductRules(params?: Record<string, unknown>) {
  return apiGet<{ items: WorkProductRule[] }>(
    '/api/v1/admin/worker-platform/product-rules',
    params,
  )
}

export function saveAdminWorkProductRule(payload: {
  ruleKey: string
  provider?: string
  platform?: string
  shopId?: string
  skuCode?: string
  productName?: string
  matchType?: string
  categoryId?: number
  enabled?: boolean
  autoCreate?: boolean
  rewardAmount?: number
  requiredDepositAmount?: number
  depositThresholdAmount?: number
  sharingEnabled?: boolean
  sharingTotalQuantity?: number
  sharingUnitReward?: number
  sharingTotalAmount?: number
  timeoutMinutes?: number
  timeoutPolicy?: string
  fieldsText?: string
  sortOrder?: number
}) {
  return apiPost<{ rule: WorkProductRule }>(
    '/api/v1/admin/worker-platform/product-rules',
    payload,
  )
}

export function reviewAdminWorkerUser(
  workerId: number,
  payload: { status: string; reviewNote?: string; levelId?: number },
) {
  return apiPost<{ worker: WorkerUser }>(
    `/api/v1/admin/worker-platform/workers/${workerId}/review`,
    payload,
  )
}

export function creditAdminWorkerWallet(
  workerId: number,
  payload: { amount: number; note?: string },
) {
  return apiPost<{ wallet: Record<string, unknown> }>(
    `/api/v1/admin/worker-platform/workers/${workerId}/wallet-credit`,
    payload,
  )
}

export function fetchAdminWorkerFinanceConfig() {
  return apiGet<WorkerFinanceConfig>('/api/v1/admin/worker-platform/finance-config')
}

export function saveAdminWorkerFinanceConfig(payload: {
  depositUnfreezeDays?: number
  recharge?: {
    enabled?: boolean
    channelName?: string
    accountName?: string
    accountNo?: string
    qrCodeImage?: unknown
    instructions?: string
  }
  withdraw?: {
    enabled?: boolean
    instructions?: string
  }
}) {
  return apiPost<WorkerFinanceConfig>('/api/v1/admin/worker-platform/finance-config', payload)
}

export function fetchAdminWorkerFinanceRequests(params?: Record<string, unknown>) {
  return apiGet<WorkerListResponse<WorkerFinanceRequest>>(
    '/api/v1/admin/worker-platform/finance-requests',
    params,
  )
}

export function reviewAdminWorkerFinanceRequest(
  requestId: number,
  payload: { status: 'approved' | 'rejected' | 'cancelled'; reviewedNote?: string; note?: string },
) {
  return apiPost<{ request: WorkerFinanceRequest }>(
    `/api/v1/admin/worker-platform/finance-requests/${requestId}/review`,
    payload,
  )
}

export function fetchAdminWorkOrders(params?: Record<string, unknown>) {
  return apiGet<WorkerListResponse<WorkOrder>>(
    '/api/v1/admin/worker-platform/orders',
    params,
  )
}

export function createAdminMockWorkOrder(payload: {
  platformOrderId?: string
  productName?: string
  rewardAmount?: number
  materialComplete?: boolean
}) {
  return apiPost<{ order: WorkOrder }>(
    '/api/v1/admin/worker-platform/orders/mock',
    payload,
  )
}

export function syncAdminWorkerOrdersFromSource(payload: {
  platformOrderId?: string
  orderId?: number
}) {
  return apiPost<{
    created: WorkOrder[]
    skipped: Array<{ orderItemId: number; reason: string }>
    createdCount: number
    skippedCount: number
  }>('/api/v1/admin/worker-platform/source-orders/sync', payload)
}

export function submitAdminWorkOrderMaterial(
  workOrderId: number,
  fields: Record<string, string>,
  screenshots?: UploadedFile[],
) {
  return apiPost<{ order: WorkOrder; complete: boolean }>(
    `/api/v1/admin/worker-platform/orders/${workOrderId}/material`,
    { fields, screenshots },
  )
}

export function publishAdminWorkOrder(workOrderId: number) {
  return apiPost<{ order: WorkOrder }>(
    `/api/v1/admin/worker-platform/orders/${workOrderId}/publish`,
  )
}

export function updateAdminWorkOrder(
  workOrderId: number,
  payload: {
    productName?: string
    platformOrderId?: string
    categoryId?: number | null
    rewardAmount?: number
    requiredDepositAmount?: number
    fieldsText?: string
    timeoutMinutes?: number
    timeoutPolicy?: string
  },
) {
  return apiPut<{ order: WorkOrder }>(
    `/api/v1/admin/worker-platform/orders/${workOrderId}`,
    payload,
  )
}

export function deleteAdminWorkOrder(workOrderId: number) {
  return apiDelete<{ deleted: boolean }>(
    `/api/v1/admin/worker-platform/orders/${workOrderId}`,
  )
}

export function unpublishAdminWorkOrder(workOrderId: number) {
  return apiPost<{ order: WorkOrder }>(
    `/api/v1/admin/worker-platform/orders/${workOrderId}/unpublish`,
  )
}

export function fetchAdminWorkOrderSharing(workOrderId: number) {
  return apiGet<{ order: WorkOrder; shares: WorkOrderShare[] }>(
    `/api/v1/admin/worker-platform/orders/${workOrderId}/sharing`,
  )
}

export function updateAdminWorkOrderSharing(
  workOrderId: number,
  payload: {
    enabled: boolean
    totalQuantity: number
    unitReward: number
    totalAmount?: number
  },
) {
  return apiPost<{ order: WorkOrder }>(
    `/api/v1/admin/worker-platform/orders/${workOrderId}/sharing`,
    payload,
  )
}

export function markAdminWorkOrderProblem(workOrderId: number, note: string) {
  return apiPost<{ order: WorkOrder }>(
    `/api/v1/admin/worker-platform/orders/${workOrderId}/problem`,
    { note },
  )
}

export function resolveAdminProblemWorkOrder(
  workOrderId: number,
  payload: {
    action: 'return_to_worker' | 'reopen' | 'cancel_release' | 'cancel_deduct'
    note: string
  },
) {
  return apiPost<{ order: WorkOrder }>(
    `/api/v1/admin/worker-platform/orders/${workOrderId}/problem/resolve`,
    payload,
  )
}

export function acceptAdminWorkOrder(workOrderId: number) {
  return apiPost<{ order: WorkOrder }>(
    `/api/v1/admin/worker-platform/orders/${workOrderId}/accept`,
  )
}

export function deductAdminWorkOrderPendingDeposit(
  workOrderId: number,
  payload: { amount: number; note: string },
) {
  return apiPost<{ deductedAmount: number }>(
    `/api/v1/admin/worker-platform/orders/${workOrderId}/deduct-pending-deposit`,
    payload,
  )
}
