import { apiClient } from '@/shared/api/client'
import type { ApiResponse, PaginatedResult } from '@/shared/types/types'

export type QrCodeStatus = 'unused' | 'used' | 'disabled'
export type QrCodeBooleanFilter = 'true' | 'false'
export type QrCodeExpireStatus = 'valid' | 'expired' | 'permanent' | 'expiring_soon'

export interface ChatQrCode {
  id: number
  image_url: string
  group_name: string
  status: QrCodeStatus
  conversation_id: number | null
  bound_conversation_title: string
  used_at: string | null
  expires_at: string | null
  created_by: number
  note: string
  wecom_renamed: boolean
  created_at: string
  updated_at: string
}

export interface QrCodeStats {
  unused_count: number
  used_count: number
  disabled_count: number
  total_count: number
}

export interface QrCodeOcrResult {
  group_name: string
  candidates: string[]
  raw_text: string
}

export interface OCRJobRecord {
  paddle_job_id: string
  status: 'submitted' | 'running' | 'done' | 'failed'
  result: QrCodeOcrResult | null
  error: string
}

export interface QrCodeListQuery {
  status?: QrCodeStatus
  keyword?: string
  wecom_renamed?: QrCodeBooleanFilter
  bound?: QrCodeBooleanFilter
  expire_status?: QrCodeExpireStatus
  created_start?: string
  created_end?: string
  page?: number
  limit?: number
}

export interface CreateQrCodePayload {
  image_url: string
  group_name?: string
  note?: string
  expires_at?: string | null
}

export interface UpdateQrCodePayload {
  image_url?: string
  group_name?: string
  note?: string
  status?: QrCodeStatus
  wecom_renamed?: boolean
  expires_at?: string | null
  clear_expires_at?: boolean
}

export interface BatchDeleteQrCodeResult {
  deleted: number
}

export async function fetchQrCodes(query: QrCodeListQuery = {}) {
  const { data } = await apiClient.get<ApiResponse<PaginatedResult<ChatQrCode>>>(
    '/admin/chats/qrcodes',
    {
      params: {
        status: query.status || undefined,
        keyword: query.keyword?.trim() || undefined,
        wecom_renamed: query.wecom_renamed || undefined,
        bound: query.bound || undefined,
        expire_status: query.expire_status || undefined,
        created_start: query.created_start || undefined,
        created_end: query.created_end || undefined,
        page: query.page || 1,
        limit: query.limit || 20,
      },
      silent: true,
    }
  )
  return data.data
}

export async function fetchQrCodeStats() {
  const { data } = await apiClient.get<ApiResponse<QrCodeStats>>('/admin/chats/qrcodes/stats', {
    silent: true,
  })
  return data.data
}

export async function createQrCode(payload: CreateQrCodePayload) {
  const { data } = await apiClient.post<ApiResponse<ChatQrCode>>('/admin/chats/qrcodes', payload)
  return data.data
}

export async function batchCreateQrCodes(items: CreateQrCodePayload[]) {
  const { data } = await apiClient.post<ApiResponse<ChatQrCode[]>>('/admin/chats/qrcodes/batch', {
    items,
  })
  return data.data
}

export async function recognizeQrCodeGroupName(file: File) {
  const form = new FormData()
  form.append('file', file)
  const { data } = await apiClient.post<ApiResponse<QrCodeOcrResult>>(
    '/admin/chats/qrcodes/ocr-group-name',
    form,
    {
      headers: { 'Content-Type': 'multipart/form-data' },
      silent: true,
    }
  )
  return data.data
}

export async function submitOCRJob(file: File) {
  const form = new FormData()
  form.append('file', file)
  const { data } = await apiClient.post<ApiResponse<{ job_id: string }>>(
    '/admin/chats/qrcodes/ocr-group-name/async',
    form,
    {
      headers: { 'Content-Type': 'multipart/form-data' },
      silent: true,
    }
  )
  return data.data
}

export async function getOCRJobResult(jobId: string) {
  const { data } = await apiClient.get<ApiResponse<OCRJobRecord>>(
    `/admin/chats/qrcodes/ocr-group-name/async/${jobId}`,
    { silent: true }
  )
  return data.data
}

export async function updateQrCode(id: number, payload: UpdateQrCodePayload) {
  const { data } = await apiClient.patch<ApiResponse<ChatQrCode>>(
    `/admin/chats/qrcodes/${id}`,
    payload
  )
  return data.data
}

export async function deleteQrCode(id: number) {
  const { data } = await apiClient.delete<ApiResponse<null>>(`/admin/chats/qrcodes/${id}`)
  return data.data
}

export async function batchDeleteQrCodes(ids: number[]) {
  const { data } = await apiClient.post<ApiResponse<BatchDeleteQrCodeResult>>(
    '/admin/chats/qrcodes/batch-delete',
    { ids }
  )
  return data.data
}
