import { apiDelete, apiGet, apiPost, apiPut } from '@/lib/http'
import type {
  CollectLookupResponse,
  UploadedFile,
  WorkOrder,
  WorkOrderEvent,
  WorkOrderShare,
  WorkerFinanceRequest,
  WorkerCancelRequest,
  WorkerCancelRequestRisk,
  WorkerAnnouncementConfig,
  WorkerOrderFeedback,
  WorkerAfterSalesCase,
  WorkerHallOrdersResponse,
  WorkerLeaderboardResponse,
  WorkerLeaderboardPeriod,
  WorkerListResponse,
  WorkerLoginResponse,
  WorkerOrderOverviewResponse,
  WorkerProfileResponse,
  WorkerSessionDevice,
  WorkerUser,
  WorkerWalletLedger,
} from '@/types/worker-platform'
import { getWorkerDeviceId } from '@/utils/worker-auth'

export function sendWorkerSmsCode(payload: { phone: string }) {
  return apiPost<{ sent: boolean; expiresInSeconds: number; provider: string }>(
    '/api/v1/worker/auth/sms-code',
    payload,
  )
}

export function registerWorker(payload: {
  phone: string
  code: string
  password: string
  displayName: string
  inviteCode?: string
}) {
  return apiPost<{ worker: WorkerUser; reviewRequired: boolean }>(
    '/api/v1/worker/auth/register',
    payload,
  )
}

export function sendWorkerPasswordResetSmsCode(payload: { phone: string }) {
  return apiPost<{ sent: boolean; expiresInSeconds: number; provider: string }>(
    '/api/v1/worker/auth/password-reset/sms-code',
    payload,
  )
}

export function resetWorkerPassword(payload: { phone: string; code: string; password: string }) {
  return apiPost<{ worker: WorkerUser; reloginRequired: boolean }>(
    '/api/v1/worker/auth/password-reset',
    payload,
  )
}

export function loginWorker(payload: { username: string; password: string }) {
  const userAgent = navigator.userAgent
  const isMobile = /Android|iPhone|iPad|iPod|Mobile/i.test(userAgent)
  return apiPost<WorkerLoginResponse>('/api/v1/worker/auth/login', {
    ...payload,
    deviceId: getWorkerDeviceId(),
    deviceType: isMobile ? 'mobile' : 'pc',
    deviceName: isMobile ? '手机浏览器' : 'PC 浏览器',
  })
}

function buildWorkerDevicePayload() {
  const userAgent = navigator.userAgent
  const isMobile = /Android|iPhone|iPad|iPod|Mobile/i.test(userAgent)
  return {
    deviceId: getWorkerDeviceId(),
    deviceType: isMobile ? 'mobile' : 'pc',
    deviceName: isMobile ? '手机浏览器' : 'PC 浏览器',
  }
}

export function sendWorkerLoginSmsCode(payload: { phone: string }) {
  return apiPost<{ sent: boolean; expiresInSeconds: number; provider: string }>(
    '/api/v1/worker/auth/login/sms-code',
    payload,
  )
}

export function loginWorkerBySmsCode(payload: { phone: string; code: string }) {
  return apiPost<WorkerLoginResponse>('/api/v1/worker/auth/login/sms', {
    ...payload,
    ...buildWorkerDevicePayload(),
  })
}

export function fetchWorkerSessions() {
  return apiGet<WorkerDeviceLimitsResponse>('/api/v1/worker/auth/devices')
}

export function deleteWorkerSession(sessionId: string) {
  return apiDelete<{ deleted: boolean }>(`/api/v1/worker/auth/devices/${sessionId}`)
}

export function manageWorkerSessions(payload: { username: string; password: string }) {
  return apiPost<WorkerDeviceLimitsResponse>('/api/v1/worker/auth/devices/manage/list', payload)
}

export type WorkerDeviceLimitsResponse = {
  maxDevices: number
  maxDevicesByType: { pc: number; mobile: number }
  deviceCounts: { pc: number; mobile: number }
  items: WorkerSessionDevice[]
}

export function deleteWorkerSessionWithCredentials(payload: {
  username: string
  password: string
  sessionId: string
}) {
  return apiPost<{ deleted: boolean }>('/api/v1/worker/auth/devices/manage/delete', payload)
}

export function fetchWorkerSession() {
  return apiGet<{
    authenticated: boolean
    expiresAt: string
    worker: WorkerUser
  }>('/api/v1/worker/auth/session')
}

export function logoutWorker() {
  return apiPost<{ success: boolean }>('/api/v1/worker/auth/logout')
}

export function fetchWorkerProfile() {
  return apiGet<WorkerProfileResponse>('/api/v1/worker/profile')
}

export function fetchWorkerAnnouncement() {
  return apiGet<WorkerAnnouncementConfig>('/api/v1/worker/announcement')
}

export function fetchWorkerWalletLedgers(params?: Record<string, unknown>) {
  return apiGet<WorkerListResponse<WorkerWalletLedger>>(
    '/api/v1/worker/profile/wallet-ledgers',
    params,
  )
}

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

export function createWorkerRechargeRequest(payload: {
  amount?: number
  note?: string
  paidAt?: string
  proofFiles?: UploadedFile[]
}) {
  return apiPost<{ request: WorkerFinanceRequest }>(
    '/api/v1/worker/profile/recharge-requests',
    payload,
  )
}

export function createWorkerWithdrawRequest(payload: {
  amount?: number
  accountChannel: string
  note?: string
}) {
  return apiPost<{ request: WorkerFinanceRequest }>(
    '/api/v1/worker/profile/withdraw-requests',
    payload,
  )
}

export function createWorkerWithdrawalAccount(payload: {
  accountChannel: string
  accountName: string
  accountNo?: string
  alipayQrCodeImages?: UploadedFile[]
  wechatQrCodeImages?: UploadedFile[]
}) {
  return apiPost('/api/v1/worker/profile/withdrawal-account', payload)
}

export function saveWorkerAlipayWithdrawalQrCode(payload: { alipayQrCodeImages: UploadedFile[] }) {
  return apiPut('/api/v1/worker/profile/withdrawal-account/alipay-qr-code', payload)
}

export function changeWorkerPassword(payload: { currentPassword: string; newPassword: string }) {
  return apiPost<{ worker: WorkerUser; reloginRequired: boolean }>(
    '/api/v1/worker/profile/change-password',
    payload,
  )
}

export function renameWorkerAccount(payload: { displayName: string }) {
  return apiPost<{ worker: WorkerUser; reloginRequired: boolean }>(
    '/api/v1/worker/profile/rename',
    payload,
  )
}

export function fetchWorkerHallOrders(params?: Record<string, unknown>) {
  return apiGet<WorkerHallOrdersResponse>('/api/v1/worker/hall/orders', params)
}

export function fetchWorkerHallLeaderboard(period: WorkerLeaderboardPeriod = 'all') {
  return apiGet<WorkerLeaderboardResponse>('/api/v1/worker/hall/leaderboard', { period })
}

export function grabWorkerOrder(workOrderId: number) {
  return apiPost<{ order: WorkOrder }>(`/api/v1/worker/hall/orders/${workOrderId}/grab`)
}

export function joinWorkerSharingOrder(workOrderId: number, payload: { quantity: number }) {
  return apiPost<{ share: WorkOrderShare }>(
    `/api/v1/worker/hall/orders/${workOrderId}/join-sharing`,
    payload,
  )
}

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

export function fetchWorkerMyOrderOverview() {
  return apiGet<WorkerOrderOverviewResponse>('/api/v1/worker/orders/overview')
}

export function fetchWorkerMyOrderEvents(workOrderId: number) {
  return apiGet<{ items: WorkOrderEvent[] }>(`/api/v1/worker/orders/${workOrderId}/events`)
}

export function fetchWorkerCancelRequests() {
  return apiGet<{ risk: WorkerCancelRequestRisk; items: WorkerCancelRequest[] }>(
    '/api/v1/worker/orders/cancel-requests',
  )
}

export function submitWorkerCancelRequest(workOrderId: number, payload: { reason: string }) {
  return apiPost<{ request: WorkerCancelRequest; risk: WorkerCancelRequestRisk }>(
    `/api/v1/worker/orders/${workOrderId}/cancel-requests`,
    payload,
  )
}

export function fetchWorkerOrderFeedbacks() {
  return apiGet<{ items: WorkerOrderFeedback[] }>('/api/v1/worker/orders/feedbacks')
}

export function fetchWorkerAfterSalesCases() {
  return apiGet<{ items: WorkerAfterSalesCase[] }>('/api/v1/worker/orders/after-sales-cases')
}

export function submitWorkerAfterSalesCaseResponse(
  caseId: number,
  payload: { response?: string; files?: UploadedFile[] },
) {
  return apiPost<{ case: WorkerAfterSalesCase }>(
    `/api/v1/worker/orders/after-sales-cases/${caseId}/response`,
    payload,
  )
}

export function submitWorkerOrderFeedback(workOrderId: number, payload: { content: string }) {
  return apiPost<{ feedback: WorkerOrderFeedback }>(
    `/api/v1/worker/orders/${workOrderId}/feedbacks`,
    payload,
  )
}

export function markWorkerOrderRead(workOrderId: number, options: { materialSeen?: boolean } = {}) {
  return apiPost<{ viewedAt: string; isUnread: false }>(
    `/api/v1/worker/orders/${workOrderId}/read`,
    { materialSeen: options.materialSeen === true },
  )
}

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

export function submitWorkerAcceptance(
  workOrderId: number,
  payload: { note?: string; imageUrls?: string[]; files?: UploadedFile[] },
) {
  return apiPost<{ order: WorkOrder }>(
    `/api/v1/worker/orders/${workOrderId}/submit-acceptance`,
    payload,
  )
}

/** 好友赠送模式：提交打手本人资料（昵称/ID/区服/系统 + 主页截图） */
export function submitWorkerGiftMaterial(
  workOrderId: number,
  payload: { fields: Record<string, string>; screenshots: UploadedFile[]; note?: string },
) {
  return apiPost<{ order: WorkOrder }>(
    `/api/v1/worker/orders/${workOrderId}/gift-material`,
    payload,
  )
}

export function remindWorkerAcceptance(workOrderId: number) {
  return apiPost<{ reminderCount: number; nextRemindAt: string }>(
    `/api/v1/worker/orders/${workOrderId}/remind-acceptance`,
  )
}

export function saveWorkerAcceptanceDraft(
  workOrderId: number,
  payload: { note?: string; imageUrls?: string[]; files?: UploadedFile[] },
) {
  return apiPost<{ order: WorkOrder }>(
    `/api/v1/worker/orders/${workOrderId}/acceptance-draft`,
    payload,
  )
}

export function supplementWorkerAcceptedOrderEvidence(
  workOrderId: number,
  payload: { files: UploadedFile[] },
) {
  return apiPost<{ order: WorkOrder }>(
    `/api/v1/worker/orders/${workOrderId}/acceptance-evidence`,
    payload,
  )
}

export function lookupCollectOrder(orderNo: string) {
  return apiPost<CollectLookupResponse>('/api/v1/collect/lookup', { orderNo })
}

export function submitCollectOrder(payload: {
  orderNo: string
  workOrderId?: number
  fields: Record<string, string>
  screenshots?: UploadedFile[]
}) {
  return apiPost<{ complete: boolean; order: Record<string, unknown> }>(
    '/api/v1/collect/submit',
    payload,
  )
}
